First look at a piece of code:
Public classDogtest {//created objects: variety, color, age PublicString breed; PublicString color; Public intAge ; //Creating a construction method PublicDogtest (String newbreed,string Newcolor,intnewage) {Breed=Newbreed; Color=Newcolor; Age=NewAge; } //create a common method Public voiddogfeature () {System.out.println ("This is a" +breed+ ", The color is" +color+ ", there is" +age+ "years old.); } //Create a main function Public Static voidMain (string[] args) {//Creating ObjectsDogtest dog =NewDogtest ("Golden Hair", "yellow", 2); //Call Objectdog.dogfeature (); }}
The above created a dogtest class, there are construction methods and common methods, the code is very simple, when the beginning of contact, there will be confused place.
1. Characteristics of the construction method
Both the user-defined constructor and the default constructor are primarily characterized by the following:
①. Automatically executes when an object is created;
②. The function name of the constructor is the same as the class name;
③. No return value type, no return value;
④. Constructors cannot be explicitly called. 2. The role of the construction method:
Constructors are primarily used to perform some initialization of object properties when creating objects, and when creating
Object, the object automatically calls its constructor. In general, the constructors have the following three aspects
The role of:
Establishes an identifier for the created object;
Open up memory space for object data members;
Completes initialization of the object data member.
Java's Construction method