Default constructor in Java? - java

What is the purpose of the default constructor in java
class Bike1 {
Bike1() {
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.

Your example provides a constructor,
Bike1(){System.out.println("Bike is created");}
which means you do not get a default constructor. A default constructor is inserted if you do not provide any constructor. Finally, Bike1 is a no-args constructor with package level (or default) access permission and appears to display a message when an instance of Bike1 is created.

Default constructor means that when you don't create any constructor for your class, the compiler automatically creates a default constructor (with no parameters) to your class at the time of compilation.
In your example you created a constructor. The constructor does not create any objects, it initialize the object.

Default constructors allow you to create objects with known, default settings and behavior. If you call a constructor with arguments, you are creating a custom object. But calling the default constructor will create objects with identical properties every time it is used.
Typically, a default constructor with "no code" doesn't need any code; it already has all the information it needs to create the object.
Remember that default constructor and a constructor with no-args are different.
Since you are defining a constructor Bike1(){} here, the default constructor will loose it's scope and will not be generated automatically.

The default constructor is the no-argument constructor automatically generated unless you define another constructor. It initialises any uninitialised fields to their default values...
follow this link.. Java default constructor

Default constructor have no arguments(parameters) and constructor name is same as class name.It will invoke at the time of object creation.
Example:
class Display{
Display(){
System.out.println("Default Constructor");
}
}
class constructor{
public static void main(String args[]){
Display dis=new Display();
}
}
Output:
Default Constructor
Because when the time of object creation default constructor will invoke automatically.

First thing we need to know that default constructor and no argument constructor are both different things. The no argument constructor is one which we declare inside the class where we actually may or may not write the functionality. The default constructor is one which will be called after object creation. The main purpose of this is to initialize the attributes of the object with their default values.
Java compiler provides a default constructor by default if there is no constructor available in the class

Related

What does the default constructor really do? [duplicate]

This question already has answers here:
What is the actual use of the default constructor in java?
(7 answers)
Closed 4 years ago.
There is something that I don't understand about the real role of the default constructor in java. In the official tutorial about object creation :
Creating Objects
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.
And in the docs about the Default Constructor (§8.8.9)
8.8.9. Default Constructor
If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
So even the default constructor of the class Object has an empty body. And I know that the default constructor does NOT initialize fields to their default values, because it's the compiler who does that :
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler.
What I don't understand is, if we didn't declare a constructor, what does the default constructor really do ?
what does the default constructor really do?
It calls super(). As per all your quotations. And does nothing else. JLS #8.8.9:
If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
i.e. it does nothing else. For those who believe it initializes instance variables please see JLS #12.5 where the contrary is asserted.
In Java, if you don´t declare any constructor the compiler create a default constructor and this constructor call to super() method, that is parents constructor. And in this process, inits instance variables like no-default constructors.
What I don't understand is, if we didn't declare a constructor, what
does the default constructor really do ?
By default, if no constructor is declared, a class has a default constructor with no args. I think that's why, by default all constructor calls super(). It follows probably the convention over configuration principle.
Whatever you declare a public constructor or you don't declare at all constructor, first instruction of the constructor is super().
That's why if you define in a class MyClass a constructor with args MyClass(String s) without keeping a constructor with no argument, constructor of MyClass subclasses cannot compile while it doesn't precise in their first instruction, the call to an existing parent constructor, in the exemple, it would be super(String ...).
Here an example :
public class MyClassWithNoArg{
public MyClassWithNoArg(){
}
}
MyClassWithNoArg constructor calls super() in this first instruction even if it not specified in the source code.
It is as if it is written in this way :
public class MyClassWithNoArg{
public MyClassWithNoArg(){
super();
}
}
Imagine now another class MyClassWithArg:
public class MyClassWithArg{
public MyClassWithNoArg(String s){
}
}
And MySubclass a subclass of MyClassWithArg
public class MySubclass extends MyClassWithArg{
public MySubclass (String s){
}
public MySubclass (){
}
}
In both cases, it will not compile since as explained previously all constructors call by default the default constructor (super()) of their parent but here the parent,MyClassWithArg, has no constructor with no arg. So, it doesn't compile.
So to solve the problem, you have to call the super constructor which exists.
public class MySubclass extends MyClassWithArg{
public MySubclass (String s){
super(s);
}
public MySubclass (){
super("");
}
}
Now, compilation is OK.
Without constructor no one can create a object of a class. Now if programmer does not add any constructor with a class then java compiler added a constructor with that class before compilation,which is known as default constructor in java.
But if programmer adds any kind of constructor(with argument or without argument) then that becomes user defined constructor and no constructor 'll be added via java compiler.
Now question is what does constructor do.
allocates memory for new object
if user defines any other operation like initialising variable that is done.

What does this function do in Java?

public class TransparentProxy {
private static ProxyServer _proxyserver = null;
private static TransparentProxy _instance = null;
public TransparentProxy() {
}
public static void main(String args[]) throws Exception {
TransparentProxy.getInstance();
}
I understand everything except the public TransparentProxy() {}. Why is it empty? What is its purpose? Why is it exempt from having a return type?
I have looked it up but can't get an exact answer. Thanks
From the tutorial of the initial part of - Learning the Java Language
A class contains constructors that are invoked to create objects from the class blueprint.
Constructor declarations look like method declarations—except that they use the name of the class
and have no return type.
You don't have to provide any constructors for your class, but you must be careful when doing this.
The compiler automatically provides a no-argument, default constructor for any class without
constructors. This default constructor will call the no-argument constructor of the superclass.
It looks like you've not read through the basics of Java language yet, you should go through them.
This is an empty constructor. It has no return types and named as the class name.
An empty constructor is needed to create a new instance via reflection by your persistence framework. If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default.
public TransparentProxy() {} ---is a Constructor
Java constructors are the methods with the same name as the Class with no return type/value. They are called or invoked when an object of class is created and can't be called explicitly. An object of a class is created using the new keyword. Ex: TransparentProxy proxy = new TransparentProxy();
Three types of Constructors are present.
1. Default Constructor
JVM internally declares a constructor when no constructor in specified. This is to allow a class to create an instance of it. Also, an Interface in Java does not have a constructor and hence no instances/object can be created.
2. Zero argument Constructor
A constructor defined with no arguments is called a Zero argument Constructor. You may use it to initialize variables to some value to begin with. All objects/instances of the class will have the same initial values.
3. Constructor with arguments
Its a constructor defined with arguments which initialize the variables of the class at the time of object creation. Every object/instance created of that class will have different initial values depending on the values passed to the constructor.
A constructor can be overloaded with different type of arguments or the number of arguments.
It cannot be overrided in a sub class.
Read here -- Why do constructors not return values?

Why Default constructor need to declare in POJO file which has Parameterized Constructor while instantiating Object?

Suppose I have one POJO class User with a constuctor public User(int id, String name){...}.
But when I instantiate the User object like User u=new User() with no parameter Eclipse gives error like The constructor User() is undefined. But it works fine when I have no parameterized Constructor. Can someone please explain why It requires to define default constructor?
The default (no-parameter) constructor is ONLY provided if you have provided no others. If you define even a single constructor for your class, you MUST use one of the explicitly defined (ie, in your code) constructors to instantiate the object. You can, of course, define your own zero-parameter, empty constructor if that works for what you're trying to do.
Edit:
Answer of why?
The compiler provides a default constructor so that the Object can be Instantiated when there are no constructors defined. But if you have defined a parametric constructor, it means that when you create a new instance of that class, its variables should initialized with the parameters you have passed(or do something similar). Without those initializations, the object might not behave in an expected way. Hence the compiler prevents such things from happening by not defining a default constructor(when you have defined one).
The no-arg constructor will be automatically added by the compiler if no constructor is provided by the developer. However, as soon as you put your own custom parameterized constructor, the compiler stops adding default constructor for you.
In this scenario, if you still want to use your no-arg constructor, you have to provide it yourself explicitly:
public User() {
}
public User(int id, String name) {
}
The logic behind this is that: if you define your own parametrized constructor, you are declaring that the parameters listed in the constructor is required to construct an object of the class. Therefore you are also implicitly declares if the user of your library do not provide these two parameters, the object shouldn't be able to construct. Thus the compiler will not add the no-arg constructor for you.
If you want to also declare that your class can still work if none of the specified parameters in the parametrized constructor is provided and you (no arg), then you have the explicitly declare that by providing the non-arg constructor yourself.
I am giving answer so late, but let's try to share with you what i know:
When you don't provide constructor compiler provides constructor. Why ? Because it is sure you are going to initialize your object with no argument constructor only. So compiler does it for you.
When you provide parameterised constructor, then compiler doesn't know which constructor you will use to initialize your object. So compiler does not provide for you one no-argument constructor. So you have to write explicitly.
Hope it will help you.
The compiler automatically provides a no-argument, default constructor for any class without constructors but if you explicitly provide any constructor with arguments then compiler will not provide a default constructor mainly due to security reasons.
So what you can do is
public User(int id, String name){...}
public User(){this(defualtID,defaultName)};
Java compiler automatically provides a no-parameter, default constructor for any class without constructors. If there is no constructor defined in your class then Java compiler will add a no parameter constructor in your generated class file. But if there is a constructor with parameter in your class, then you need to write the no-parameter constructor, compiler will not add it.

declaring and invoking constructor

Below code shows error at line 4
class MyClass{
public MyClass(int a){ } //Line 2
public static void main(String a[]){
MyClass n = new MyClass(); //Line 4
System.out.print("TRUE");
}
}
But, once i remove line 2, it runs without any error. Although, I didn't add default constructor. Why ?
Remember that Compiler provides your class with a default constructor only if you have not given any explicit constructor. As soon as you declare your own constructor, parameterized or 0-arg, the compiler won't give you the default constructor.
Now in your code, you have declared a parameterized constructor, compiler won't give a default one. So, you actually don't have any 0-arg constructor, and hence you cannot use it.
once i remove line 2, it runs without any error. Although, I didn't
add default constructor. Why ?
Of course if you remove your line 2, then you haven't declared any explicit constructor, in which case Compiler adds a default 0-arg constructor, and hence your code succeeds. Also note that the default constructor is the one give by compiler. When you declare your 0-arg constructor, it's not called a default one, but just a 0-arg constructor.
So, whenever you are declaring a parameterized constructor, make sure that you also declare a 0-arg constructor explicitly, if of course you are using it.
public MyClass() {
}
Each class will have an implicit default constructor, which takes no arguments. However, when you declare a constructor with args, the default constructor is omitted. Hence
MyClass n = new MyClass();
will fail to compile.
Note that a class can have multiple constructors, and you can declare the default no-arg constructor explicitly if you have other constructors. e.g.
class MyClass{
public MyClass(int a){ }
public MyClass(String a){ }
public MyClass(){ } // no-arg declaration now required
}
That's because once you declared a constructor with parameters, the default constructor without parameters is no longer available.
In your class default constructor is missing , it contains only parameterised constructor. But you are initializing using default constructor. So you will get error at line 4.
Add default constructor too in your code as blow
as your creating object with default constructor MyClass n = new MyClass(); your code should have default constructor.
public MyClass(){ }
now it will work with out any error.
If you want to go with paramertised constructor, then create object as below.
MyClass n = new MyClass(pass parameter here);
if you have no constructors defined in the class then only compiler will automatically insert default constructor (no-args)
Read the last paragraph at http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
When you create parameterized cunstructor then default constructor is removed unless you create you own default constructor.
Hence you have to create constructor as below.
public MyClass(){}

Why should the derived class constructor always access base class constructor?

I saw this question in one of my question papers:
Why should the derived class constructor always access base class constructor?
I'm wondering whether the question is valid?
So that you may have a valid object of type "Base" before you start messing with the inherited functionality in your derived object!
It's not valid. There's no 'should' about it: it must, and the compiler enforces it, by calling the base class's default constructor if it exists, and giving you a compile error if it doesn't, which forces you to call one of the existing constructors.
There is one exception to always, a default constructor in a superclass isn't usually called explicit.
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
Because the base class may do work you are not aware of.
Because the base class may have members that require initialization.
Since the derived class constructor wants to inherits from the base class constructor, it is necessary to call the base class constructor. Otherwise, if you don't, you will not inherit values initialised in base class constructor.
Calling a superclass constructor is not a must but a should paired with a strong advise - as long as the superclass has a default constructor. Otherwise the compiler forces you to call at least one of the superclasses constructors.
If the default constructor is present, it's called anyway, even without an explicit super() statement in the subclasses construtor.
A visible part of class construction is the initialization of fields. But there's more under the hood (memory allocation, registration, etc). All this has to be done for all superclasses when a derived class is created.
You do not need to call constructor when there is a default constructor (i.e a no-argument constructor) present in the base class. When there is a constructor with arguments present and no default constructor, then you don't need to declare a constructor in the child class.
You only need to initialize the child class constructor when there is no default constructor present in the parent class.
Example :
class A {
public int aInstanceVariable;
public A(int aInstanceVariable) {
this.aInstanceVariable = aInstanceVariable;
}
}
class B extends A {
// In this case we have to call super in base class constructor
}
However, when public A() {} is present in class A, there is no need to initialize the child class constructor.

Categories

Resources