Java is an object-oriented language, object-oriented is not so straightforward, its design idea is to code reuse. That is, I've done something like this before, so I'm going to find the code that I could use before, and complete the part. I didn't write it again. Then there is the class.
With classes, there is code that can be reused, but how do I produce this object? This class must be instantiated (this is not the only way to produce objects, such as singleton patterns, but essentially all paths are the same). Then you need to use the constructor. That tells the program I'm going to instantiate an object now, and you'll allocate memory for me right away. Assigns the first address of memory to the class object I specified. And sometimes you need to pass parameters into the function, it's convenient to have the constructor, and the constructors can have countless. Of course, passing parameters into the object can also be other methods, such as assigning a value directly to the member variable
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 called Hello has the parameter construction method, in Java if the construction method is not written, the default is added to a parameterless constructor, but if there is already a parameterized construction 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.
When to use construction methods in Java