(Special method used to initialize object )
- A constructor in Java is a special method that is used to initialize objects.
- Constructor is a block of codes similar to the method.
- Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
- Default Constructor
- Parametrized Constructor
- Copy Constructor
class Person {
private String name; // Instance Variable
private int age; // Instance Variable
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name; // Getters for Name
}
public int getAge() {
return age; // Getters for Age
}
}
public class demo {
public static void main(String[] args) {
Person person = new Person("adam", 32); // creating object person
System.out.println("Name:" + person.getName());
System.out.println("Age:" + person.getAge());
}
}
-
This()
- this() can be used to invoke the current class constructor
- It can be passed as an argument in the method call
- It can be passed as an method in the constructor call.
-
Super()
- super() calls the parent constructor
- It can be used to call methods from the parent.
- It returned with no argument.