Constructor
- A constructor in java is a special member that is called when an object is created
- It initializes the new object state.
- It is used to set default or user-defined values for the object's attributes
- A Constructor does not have a return type , not even void
- Constructor name should be same as class name
Type of Constructor in java
1.Default Constructor
A default constructor has no parameters.
It used to assign default values to an object
If no constructor is defined
Java provides a default constructor
class Student {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name);
System.out.println(s.age);
}
}
Output
null
0
2. Parameterized Constructor or Argument Constructor
- A constructor that has parameters is known as parameterized constructor
- If we want to initialize fields of the class with our own values,then use a parameterized constructo r
public class Object {
static String name = "Raja";
static int no = 90;
String product_name;
int age;
public Object(String product_name,int age){
this.product_name = product_name;
this.age = age ;
//System.out.println("I am IRONMAN");
}
public static void main(String [] args){
Object product = new Object("Akilan",22);
Object product1 = new Object("Alagu",21);
//product.product_name = "Akilan";
// product1.product_name = "Alagu";
//product.age = 22;
//product.age = 21;
System.out.println(product.product_name);
System.out.println(product1.product_name);
System.out.println(product.age);
System.out.println(product1.age);
//System.out.println(Object.name);
//System.out.println(Object.no);
}
}
Output
Akilan
Alagu
22
21
Constructor overloading
- Same Constructor with different no of arguments or different type of arguments
- Static polymorphism
- Earily binding
- Complie time polymorphism

Top comments (0)