Constructor is also called constructor OR constructor

Scenario: in java.
The constructor must be used in conjunction with new. Cannot be discarded by the object alone. Mainly used to initialize the class.
Syntax: access modifier (method name must be the same as class name) class name () {//initialization code}; no return value.
If no constructor is written, the compiler will automatically give the class a default constructor with no parameters. If the parameterized constructor is written and the system does not provide the default parameterless constructor, if the parameterless constructor is called, an error will be thrown and no parameterless constructor is defined. If you continue to use the no-parameter construction, you need to define it in the class yourself.

Examples of construction methods with parameters
public class Cat{
String name;
int month;
double weight;
public Cat(String newName,int newMonth,double newWeight){ //The line parameter cannot have the same name as the member variable in the class (if the same name, it will Because of the near principle of assignment, the member variable is not attached to the value)
//Construction with parameters
name = newName;
month = newMonth;
weight = newWeight;
}
public static void main(String[] args){
Cat cat = new Cat ("Little Yellow Cat","2","600");
}
}

Guess you like

Origin blog.csdn.net/u010436133/article/details/61915960