constructor in java is a spacial method, that is called when object is created. Its main purpose is to initialize the object. It is used to set default or user-defined values for the object's attributes.
- A constructor has the same name as the class.
- It does not have a return type, not even void.
- It can accept parameters to initialize object properties
Rules of Constructor
- Constructor name must be the same as the class name.
- Constructors do not have a return type (not even void).
If you add a return type, it becomes a method, not a constructor.
A constructor is called once per object creation (when using new).
If no constructor is defined, Java provides a default no-arg constructor.
If you define any constructor, the default is con't provided.
Default Constructor :
Java provides this automatically if you donβt define any constructor
public class Constructor{
int age=10;
public static void main(String[] args){
Constructor obj = new Constructor();
System.out.println(obj.age);
}
}
No-Argument Constructor
You write it yourself, no parameters.
public class Constructor{
int age=10;
public Constructor(){
System.out.println("no agru constructor");
}
public static void main(String[] args){
Constructor obj = new Constructor();
System.out.println(obj.age);
}
}
Parameterized Constructor
Used to pass values at object creation and set value for arttibutes.
public class Constructor{
int age;
public Constructor(int a){
age=a;
}
public static void main(String[] args){
Constructor obj = new Constructor(19);
System.out.println(obj.age);
}
}
Top comments (0)