Features: 1. The function name is the same as the class name.
2, do not define the return value type.
3, there is no specific return value.
P.S.
Adding the return value before the constructor is just a generic function.
Function: Initializes an object.
Example:
Class person{
private String name;
private int age;
Defines the constructor//constructor of a person class
, and is the person
() {System.out.println () of the null argument
("person run");
}
public void Speak () {
System.out.println (name + ': ' + age);
}
}
Class consdemo{public
static void Main (string[] args) {
//constructor: The function//function that is invoked when the object is created
: The object can be initialized
Person p = new person ();
P.speak ();
}
P.S.
1. What is the difference between a general function and a constructor? Constructor: When an object is created, it invokes the corresponding constructor and initializes the object.
Generic function: When an object is created, it is called when a function function is required.
Constructor: When an object is created, it is invoked and called only once.
Generic function: When an object is created, it can be invoked multiple times.
2, the creation of objects must be initialized through constructors.
If a constructor is not defined in a class, then there is a default null parameter constructor in the class.
If the specified constructor is defined in the class, then the default constructor in the class is not.
3. Multiple constructors exist in the form of overloads.
Example:
Class person{
private String name;
private int age;
Person () {
name = "Baby";
Age = 1;
SYSTEM.OUT.PRINTLN ("person run");
}
If a child is born with a name of person
(String N) {
name = n;
}
If a child is born with a name and age person
(String n, int a) {
name = N;
age = A;
}
public void Speak () {
System.out.println (name + ': ' + age);
}
}
Class consdemo{public
static void Main (string[] args) {person
p1 = new Person ();
P1.speak ();
person P2 = new Person ("flourishing wealth");
P2.speak ();
Person P3 = new person ("cockroach", ten);
P3.speak ();
}