The constructor method is the one that has the same name as the class, and it can be used to initialize
class person//human {
Public person (String n,int a)//constructor method
{
name = N; age = A;
}
private string name;
private int age;
}
static void Main (string[] args) {
Person p = new person ("Zhang San", 14);//This is the function
}
A constructor is used for the new object, such as hello hello = new Hello (), which is called the no-argument construction method of Hello; Hello hello = new Hello ("Hi"), this is the invocation of the Hello parameter constructor method, in Java If you do not write the construction method, will default to add a parameterless constructor, but if you already have a parameterized constructor method, The parameterless constructor will not be added by default. If there is already an argument constructor in the Hello class, then use the hello hello = new Hello () and the object will be created with an error. This is why it is best to add a parameterless construction method to the book to emphasize the construction of parameters.
What is the construction method and its role in Java