package javaObjectOrientedProgrammingMooc;
public class Car {
private String band;
private String color;
Car(){
band = "Test";
color = "grey";
}
Car(String bandIn, String colorIn){
band = bandIn;
color = colorIn;
}
public String getBand() {
return band;
}
public String getColor() {
return color;
}
}
In the code given above, we can find there are two special function: Car() and Car(String bandIn, String colorIn), which have the same name with class and don't have return value, we call this function as constructor.
Why we need constructor?
When we create an object, we need to assign an initialization to attribute of object, which ensure it's meaningful of an object, so the best time of initialization is when create an object, so,The function of constructor is to initialize the member variable.
The statement of constructing an object is:ClassName objectName = New ClassName();So, util now, we have known the function after the key word new is constructor.
When the constructor don't have parameter, the java VM will give the defaut value to variables, otherwise, use the parameter in constructor.
![](https://i-blog.csdnimg.cn/blog_migrate/d211fa2236b1ec553e28543d79fd3c0f.png)
Summary:
The name of constructor and class is totally same.
Constructor does't have return value, so we cannot add void to modifier. Also, cannot use return modifier.
The main function of constructor is to initialize variable.
The constructor will be called by system automatically when the object created.
If we define constructor, it will use the constructor we defined, Java VM will not define a default constructor.
If we don't define constructor, the Java VM will generate a default constructor, which has the same name with class and with default value.
The constructor only can be called once.
package javaObjectOrientedProgrammingMooc;
public class testStudent {
public static void main(String[] args) {
Student peter = new Student();
peter.print(); // default value
peter.setSno("007");
peter.setSname("Leo");
peter.print();
Student james = new Student("002");
james.print();
}
}