what is constructor?
A constructor is special method used to initialize objects.
- The constructor is called when an object of a class created.
- constructor is name must match the class name.
- it cannot have a return type(like void).
- constructors can not inherited by subclass, but the constructor of the superclass can be invoked from the subclass.
- All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.
- Constructors are called only once at the time of Object creation while method(s) can be called any number of times.
- Constructor in Java can not be abstract, final, static, or Synchronized.
Types of constructors in Java
Default constructor
Parameterised Constructor
Copy constructor
➤Default constructor
- A constructor that has no parameters is known as default the constructor.
- if we create a default constructor with no arguments, the compiler does not create a default constructor
➤Parameterised constructor
- A constructor that has parameters is known as parameterized constructor.
1) Example of parameterised constructor
public class A
{
int x;
public A(int y)
{
x = y;
}
public static void main(String[] args)
{
A obj = new A(5);
System.out.println(obj.x);
}
}
2)Example of parameterised constructor (using "this" keyword)
public class A
{
int x;
public A(int x)
{
this.x=x;
}
//constructor
public static void main(String[] args)
{
A obj = new A(5);
System.out.println(obj.x);
}
}
➤Copy constructor
- Like C++, Java also supports a copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.
NOTE :
- If constructors are inherited (class is inheriting other classes) then always first parent class's constructors invoke first one by one then child classes.
- Java does not call a parameterized constructor implicitly, you need to explicitly invoke parameterised constructor.
- In Java, when you create an object of a child class, the default constructor of the parent class is implicitly called. If the parent class has a parameterized constructor and no default constructor is explicitly defined, you need to ensure that the child class constructor explicitly calls the appropriate parent constructor using the super keyword
Comments
Post a Comment