The constructor is a special method in a class. When a program creates an object from a class, its constructor is used. The name of the constructor in the class must be exactly the same as the name of the class in which it is located, and there is no type. It is allowed to write several constructors in a class, but they must ensure that their parameters are different. Different parameters means: the number of parameters is different, or the number of parameters is the same, but the type of a corresponding parameter in the parameter list is different.
Notice:
If there is no constructor written in the class, the system will default to the class having only one constructor. The default constructor has no parameters and has no statements in the method body.
If one or more constructors are defined in a class, Java does not provide a default constructor. For example: The following Point class has two constructors.
classPoint{intx,y;Point(){x=1;y=1;}Point(inta,intb){x=a;y=b;}}
It is important to note that constructors do not have types.
For example:
classPoint{intx,y;Point(){//It is a construction method x=1;y=1;}voidPoint(inta,intb){//It is not a construction method, the type of this method is voidx=a;y=b; }intPoint(){//Not a constructor, the type of this method is inreturn12;}}