A method that is automatically executed during a class instantiation is called a construction method, and it does not require you to invoke it manually. The construction method can do some initialization work during the instantiation of the class. The name of the construction method must be the same as the name of the class, and there is no return value. Each class has a constructor method. If you do not explicitly define a construction method for a class, the Java compiler will provide a default constructor for the class
The following is an example of the use of a construction method:
1 Public classdog{22String name;33intAge ;44//constructor Function55 Dog (String name1,intage1) {66 name =name1;77 Age =Age1;88 System.out.println ("Thank the Master for adopting me");99 }Ten10 One11voidbark () { ASystem.out.println ("Bark, don't come over"); -13 } -14 the15voidhungry () { -System.out.println ("Master, I'm hungry.")); -17 } -18 +19 Public Static voidMain (String arg[]) { -Dog Mydog =NewDog ("Floral", 3);//Declaration + instantiation + initialization Mydog +21st//Accessing member variables AString name =Mydog.name; at23intAge =Mydog.age; -System.out.println ("I am a puppy, my name is" + name + ", I" + Age + "old")); -25//access Method -26Mydog.bark (); -27mydog.hungry (); -28 } in29}
The result of the operation is:
Thank you, Master, for adopting me.
I'm a puppy, my name is flower, I'm 3 years old.
Bark, don't come over.
Master, I'm hungry.
Understanding of construction methods in Java