In Java, a constructor is a special method that is called when an object of a class is created. Constructors are used to initialize the state of an object, and they have the same name as the class.
There are several ways to invoke a constructor in Java:
new
operator: To create a new object using a constructor, you can use the new
operator followed by the class name and the arguments for the constructor. For example:Person p = new Person("John", 30);Source:www.lautturi.com
This will create a new Person
object with the name "John" and the age 30.
this
keyword: Within a class, you can use the this
keyword to refer to the current object. You can use the this
keyword to call another constructor in the same class. For example:public class Person { private String name; private int age; public Person() { this("John", 30); } public Person(String name, int age) { this.name = name; this.age = age; } // ... }
In this example, the Person
class has two constructors: a default constructor that takes no arguments, and a constructor that takes a String
for the name and an int
for the age. The default constructor calls the second constructor using the this
keyword and passes the default values for the name and age as arguments.
super
keyword: Within a subclass, you can use the super
keyword to call a constructor in the superclass. For example:public class Student extends Person { private String major; public Student(String name, int age, String major) { super(name, age); this.major = major; } // ... }
In this example, the Student
class is a subclass of the Person
class. It has a constructor that takes three arguments: a String
for the name, an int
for the age, and a String
for the major. The constructor calls the constructor of the superclass using the super
keyword and passes the name and age arguments to it.