What is Constructor in Java?
- Constructor is a special method that gets invoked “automatically” at the time of object creation.
- Constructor is normally used for initializing objects with default values unless different values are supplied.
- Constructor has the same name as the class name.
- Constructor cannot return values.
- A class can have more than one constructor as long as they have different signature (i.e., different input arguments).
If Constructor not defined in the class?
- If you don’t define a constructor, a default one(Zero Argument constructor) will be created by Java compiler.
- If you define any constructor for your class, no default constructor is automatically created.
Sample Examle :
public class ClassName {
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
- We can call one constructor from another using this().
- Use this to call other constructors in the same class.
this( ) :
- Use this to refer to the current object.
- Use this to invoke other constructors of the object.
public class HelloWorld
{
int i ;
String str;
HelloWorld()
{
this(2);
}
HelloWorld(int i){
this("Hai");
this.i = i;
}
HelloWorld(String str){
this.str = str;
System.out.println(str + "Welcome!!!!");
}
}How to Call Super Class constructor ?
- we can call superclass constructor Using super() keyword
- super needs to be the first line of code in the constructor of the child class.
class Base
{
Base()
{
System.out.println("Hello i'm a super class Zero Arg Constructor");
}
Base(int i)
{
System.out.println("Hello i'm a super class Arg Constructor");
}
}
class Der extends Base
{
Der()
{
super(); //Automatically call if you don't call constructor here.
System.out.println("Sub class constructor");
}
Der(int j){
super(4);
System.out.println("Hai");
}
}
Differences between method and constructor
- There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
- There is no return statement in the body of the constructor.
- The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
Differences between super() and this()
- "this" refers to the current class where as "super" refers directly to its immediate above super class.
- this() can be used to invoke a constructor of the same class.super() can be used to invoke a super class constructor
Other Java Tutorials you may like
Posted in: