1. Constructor
The name is the same as the class name. There is no return type and no return.
When an object is created, it calls the constructor. Once the constructor is created by itself,ProgramThe default constructor will not be created.
Constructor is used to initialize objects. Once an object is initialized, it is granted with features in the object constructor. However, a common function will assign features to objects later.
Package day05; class person {private string name; private int age; Public Person () {system. out. println ("name =" + name + ", age =" + age);} public person (string name) {system. out. println ("name =" + name + ", age =" + age);} public void setname (string name) {This. name = Name;} Public String getname () {return name;} public class getperson {public static void main (string [] ARGs) {person Per1 = new person (); person per2 = new person ("Lisi"); per1.setname ("xiaogui"); system. out. println (per1.getname ());}}
2. StructureCodeBlock
The construction code block takes precedence over the construction function execution. The construction code block is used to initialize all objects in a unified manner.
Class person {private string name; private int age; // construct the code block {cry ();} public person () {system. out. println ("name =" + name + ", age =" + age); // cry ();} public person (string name) {system. out. println ("name =" + name + ", age =" + age);} public void setname (string name) {This. name = Name;} public void cry () {system. out. println ("cry ...... ") ;}} public class getperson {public static void main (string [] ARGs) {person Per1 = new person (); // per1.setname (" xiaogui "); // system. out. println (Per1 );}}
3. This keyword
When a local variable conflicts with a member variable, the local variable prevails.
This: indicates the object of this class. It indicates the reference of the object to which this constructor belongs. This must be added for the same name.
Summary:
The constructor code block takes precedence over the constructor and initializes all objects.