A constructor is a kind of function called to create an object from a class. It prepares the new object for use often accepting arguments that the constructor uses to set required member variables.
Constructors usually have the same name as the class it constructs objects from.
public class Dog {
int age;
String name;
public Dog(int age, String name) {
this.age = age;
this.name = name;
}
}
The constructor Dog initializes the member variables, age and name.
public class Main {
public static void main(string[] args) {
Dog rufford = new Dog(12, "Rufford");
Dog clifford = new Dog(15, "Clifford");
System.out.println(rufford.name);
// outputs: Rufford
System.out.println(clifford.name);
// outputs: Clifford
}
}
Notice how in Java the
newkeyword is used to create a new object with a constructor.