Constructors in Java can be seen as a special method in a class. But there is a big difference between Constructor and Method. These differences can be defined in terms of purpose, syntax, and invocation. A constructor is used in the creation of an object of a class.
Purpose (Constructor Vs Method)
Constructors have only one purpose, to create an instance of a Class. This instantiation includes memory allocation and member initialization (Optional).
By contrast, Methods cannot be used to create an instance of a Class. A method is the combination of statements to perform some task and return some value (Optional).
Syntax (Constructor Vs Method)
/*
* Here Class name is ConstructorExample, So constructor name needs to be the same.
*/
public class ConstructorExample {
/*
* As below signature has the name as Class name and it doesn't contain any
* return value so it will be treated as Constructor of the class
*/
public ConstructorExample() {
System.out.println("Inside Constructor");
}
/*
* Below method will be invoked only when it is invoked implicitly.
* Method has return type along with Non Access Modifier
*/
static void method() {
System.out.println("This is in method");
}
}
The syntax of a Constructor is different than a Method as described below.
- Constructors cannot have Non Access Modifiers while Methods can.
- Constructors cannot have a return type(Including void) while Methods require it.
- The Constructor name must be the same as the Class name while Methods are not restricted.
- As per Java naming convention, Method names should be camelcase while Constructor names should start with a capital letter.
A Method can have the same name as the Class name.
Invocation (Constructor Vs Method)
There is a difference between how constructors and methods are called. Constructors cannot be called explicitly, the constructor will be invoked implicitly when the instance of the class is generated(Using a new Keyword)
Constructor Invocation Example
/*
* Here Class name is ConstructorExample, So constructor name needs to be the same.
*/
public class ConstructorExample {
/*
* As below signature has the name as Class name and it doesn't contain any
* return value so it will be treated as Constructor of the class
*/
public ConstructorExample() {
System.out.println("Inside Constructor");
}
public static void main(String args[]) {
ConstructorExample cls = new ConstructorExample();
}
}
// Output will be
// Inside Constructor
Method Invocation Example
/*
* Here Class name is ConstructorExample, So constructor name needs to be the same.
*/
public class ConstructorExample {
/*
* As below signature has the name as Class name and it doesn't contain any
* return value so it will be treated as Constructor of the class
*/
public ConstructorExample() {
System.out.println("Inside Constructor");
}
/*
* As below signature has the name as Class name and it doesn't contain any
* return value so it will be treated as Constructor of the class. But
* as it has parameter it will be called as parameterized constructor.
*/
public ConstructorExample(String str) {
System.out.println("Inside Parameterized Constructor");
}
/*
* Below method will be invoked only when it is invoked implicitly.
*/
void method() {
System.out.println("This is in method");
}
public static void main(String args[]) {
ConstructorExample cls = new ConstructorExample();
/*
* Now method will be called explicitly as below. It will execute the
* code within method.
*/
cls.method();
}
}
//The output would be Inside Constructor This is in method
A constructor in a class must have the same name as the given class. A Constructor’s syntax does not include a return type, since constructors never return a value. Constructors may also include parameters of various types. A constructor that has one or more parameters is called a parameterized constructor in Java.
When the Constructor is invoked using the new operator, the types must match those that are specified in the Constructor definition.
When no explicit constructors are provided, java provides a default constructor that takes no arguments and performs no special actions or initializations. The only action taken by the implicit default Constructor is to call the superclass constructor using the super() call.
Rules for Constructor
- A constructor cannot have a return type.
- A constructor must have the same name as that of the Class.
- Constructors cannot be marked static
- A constructor cannot be marked abstract
- A Constructor cannot be overridden.
- A Constructor cannot be final.
Default Constructor
In case the user doesn’t provide a constructor in a class (with or without parameter) JVM will provide a default constructor. This default constructor will be non-parameterized.
If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor(constructor without argument), its implementation must be provided explicitly by the user.
Any attempt to call the default constructor will be a compile-time error if an explicit default constructor is not provided in such a case.
Constructor Overloading
Like methods, constructors can also be overloaded. Since all the constructors in a class have the same name as the class, their signatures are differentiated by their parameter lists.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructor invokes the other constructor with the corresponding parameter list within the same class. Java requires that this() call must occur as the first statement in a constructor.
Constructor Chaining
An implicit super() call is included in each constructor which does not include either this() or an explicit super() call as its first statement. The super() statement is used to invoke a constructor of the superclass.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor. The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types. A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.
super() or this() construct: If used in the constructor, it must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as this() construct leads to the chaining of constructors in the same class, the super() construct leads to the chaining of subclass constructors to superclass constructors. If a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted implicitly.
If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error.
The subclasses must then explicitly call a Superclass constructor, using the super() construct with the right arguments to match the appropriate Constructor of the Superclass.
Cheatsheet
- A constructor is invoked when a new object is created.
- Constructors can also be overloaded but it can not be overridden.
- Every class has at least one constructor. If a user doesn’t provide any, JVM will provide a default no-arg constructor.
- Abstract class also has a constructor.
- A constructor must have the same name as the class.
- A constructor can’t have a return type.
- If a method with the same name as a class has a return type, it will be treated as a normal member method and not a constructor.
- A constructor can have any access modifier(All).
- A default constructor is a no-arg constructor that calls the no-arg constructor of the superclass. In case the superclass doesn’t have any no-arg constructor then it will throw a runtime exception.
- In a case where a class has the default constructor, its superclass needs to have a no-arg constructor.
- The first statement of a constructor can be either this or super but cannot be both at the same time.
- If the coder doesn’t write any this() or super() call then the compiler will add a call to super().
- super() is used to call the constructor from the superclass.
- this() is used to call a constructor from the same class.
- Instance members can be accessed only after the super constructor runs.
- Interfaces do not have constructors.
- A constructor is not inherited. Hence cannot be overridden.
- A constructor cannot be directly invoked. It will be invoked(Implicitly) when a new object is created or called by other constructors.
Good Explanation
I have a question?
Why a constructor can not have a return value?
It can not have because there is no point in having a return value. The only purpose of a constructor is to create an Object and it is called by JVM only. No one else can call it.
Wonderful points you have mentioned here, your article is very
petrified me in the learning process and provide
additional knowledge to me , maybe I can learn
more from you. Thank you
I really appreciate, the quality of tutorials you are providing.
sir Plz tell me that which is execute first constructor or init block. and why?
Hi Harsh,
I have already written an article to show the sequence of block execution. Please have a look at the same.
Link : javabeginnerstutorial.com/learn-by-example-3/order-of-execution-of-blocks-in-java/
Regards
Can you please give me your mail Id or can you please mail me at [email protected].
My ques is not reflecting in Comment section. So I am not sure whether is posted or not.
Regards,
Satnam
Hi J singh,
I have poseted the comment but it is not reflecting section ..May I know why.
It should have been published till now. What is your question?
Thanks for your reply .
Q) Does constructor return any value?
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).
I have read it that constructor can return a value but it is mentioned in this article that Constructor cannot have a return value, Please can you explain elaborately.
Hi Satnam,
I don’t know who told you that constructor can have a return type but this is completely wrong. Constructor can not have a return type.
Regards
Hi, It is mentioned clearly that Constructor shouldn’t have a access modifier. But How can a contructor be private ??
Hi Satnam,
Please let me know where have i written that Access Modifier can not applied to Constructor? Coz access modifier can be applied to constructor too. And constructor can be private too.
Regards
” If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a Superclass constructor, using the super() construct with the right arguments to match the appropriate Constructor of the Superclass”
Does this mean that if you do not explicitly define a default constructor but only the parametrized constructor, it will not throw a compile time error provided you call the super() with the corresponding arguments in the subclass similar to that of Super class constructor
Yes. You understood it correctly.
What is differnce between the implicit and explicit constructor?
If you define constructor on your own with or without argument, it is called explicit constructor. But if you don’t provide any constructor at all, JVM will provide one without argument constructor. It is called implicit constructor.
thanx for assistance
I know what is constructor, and constructor chaining. I want to know what are the types e.g what is vertical and horizontal constructor chaining.
sir, what is singleton class?
Hi Apoorva,
Please have a look at given article you will have understanding of Singleton class. In case you have further question after reading that you can mail me.
http://94.143.139.145/design-pattern/singleton-design-pattern-java/
Regards
Gautam
Sir .i am beginner in java…..this is very useful..thanks alot.. 🙂 🙂
hullo sir,i m a beginner sir i want some practical example so that i can do it on my laptop as if i am a student so need to do practice 4 clg exams
Sir very nice explaination.But you wrote that “Constructors cannot have Non Access Modifier”
and you wrote in constructor rules :-“Constructor can be Final.” I am confused.Can you please explain?
Hi Nishi,
That is a typo error. Constructor can’t be Final. Same has been resolved in the Article.
Hope it help.
Regards
Vivekanand Gautam
Can we define constructor as private?What is purpose of private constructor?
Yes, We can. Singleton is one of the use of Class having private constructor
to create a instance of a class its main purpose of a constructor.
@amithabh
As per praga said if we not use any constructor then compiler takes no argument constructor and class must follow super class Object using implicit method super(). Now class can use these important methods.
Another reason is when you create object A a=new A(), Here method A() is going to call So class A must have constructor.
Very important reason is constructor initializes class. This includes memory allocation to objects. Compiler compiles constructor and static variable in initial phase.
hiiii sir if u dnt mind will u pls explain how to trace java program
Hi,
You have mentioned constructor should not have any return type but in your code and the example I can see the return type for the constructor. Please correct me if my understanding is correct or not.
public ConstructorExample() {
System.out.println(“Inside Constructor”);
}
in example where is return type??
public is not a return type, its an access modifier.
Constructor cannot have a return type.
i am also wanted to know”how to trace java programme”
why used constructor ? and what is advantage?
not used constructor in java then what happened ……..
as far as i know, it is optional to use constructor.if user defined constructor is unavailable then compiler creates default constructor just to initialize memory location to members of class(variables).
we can use constructors in all class but not all in constructors
Whats the use of co-variant features in java?
Whats the use of assert statement over exception classes?
Its good explanation, Is there any technical reason why constructor should be the same name as class name?
I think no keyword is required if the constructor name is same as method name…
Which keyword you are talking about Gayathri?
Key words most important if u know keywords you can declaration easily
If constructor is declared as method ,then It will not implicitly call by JVM and it will act as normal method.