[Java Learning Fundamentals] Java Constructor [Java Learning Fundamentals] Java Encapsulation and Access Control

     Constructor is a special method in a class that is used to initialize instance variables of the class, and it is called automatically after the object is created (the new operator).

The characteristics of the Java constructor are as follows:

  1. The constructor name must be the same as the class name.

  2. Constructors have no return value, including void.

  3. Constructors can only be used in conjunction with the new operator.

The sample code is as follows:

1  // Rectangle.java file 
2  package com.a51work6;
 3  
4  // Rectangle class 
5  public  class Rectangle {
 6  
7      // Rectangle width 
8      int width;
 9      // Rectangle height 
10      int height;
 11      // Rectangle area 
12      int area;
 13  
14      // Construction method 
15      public Rectangle( int w, int h) {        
 16          width = w;
 17         height = h;
18         area = getArea(w, h);
19     }
20     ...
21 }

Line 15 of the code declares a constructor with two parameters w and h, which are used to initialize the two member variables width and height of the Rectangle object. Note that there is no return value in front.

default constructor

Sometimes you don't see any constructors at all in the class. For example, the User class code in this section is as follows:

1  // User.java file 
2  package com.a51work6;
 3  
4  public  class User {
 5  
6      // User name 
7      private String username;
 8  
9      // User password 
10      private String password;
 11  
12 }

From the above User class code, there are only two member variables, and no constructor can be seen, but you can still call the parameterless constructor to create a User object, because the Java virtual machine provides a parameterless default for a class without a constructor Constructor, the default constructor has no statement in its method body, and the default constructor is equivalent to the following code:

// Default constructor 
public User() {
}

There is no statement in the method body of the default constructor, so the member variables cannot be initialized, then these member variables will use the default value, and the default value of the member variable is related to the data type.

Constructor overloading

      There can be multiple constructors in a class, and they have the same name (same name as the class) and different parameter lists, so there must be an overloading relationship between them.

The example code of constructor overloading is as follows:

1  // Person.java file 
2  package com.a51work6;
 3  
4  import java.util.Date;
 5  
6  public  class Person {
 7  
8      // Name 
9      private String name;
 10      // Age 
11      private  int age;
 12      // 13 private Date birthDate 
;
 14 15 public Person(String n, int a, Date d) {        
 16          name = n;
 17      
              age = a;
18         birthDate = d;
19     }
20 
21     public Person(String n, int a) {                
22         name = n;
23         age = a;
24     }
25 
26     public Person(String n, Date d) {               
27         name = n;
28         age = 30;
29         birthDate = d;
30     }
31 
32     public Person(String n) {                       
33         name = n;
34         age = 30;
35     }
36 
37     public String getInfo() {
38         StringBuilder sb = new StringBuilder();
39         sb.append("名字: ").append(name).append('\n');
40         sb.append("年龄: ").append(age).append('\n');
41         sb.append("出生日期: ").append(birthDate).append('\n');
42         return  sb.toString();
43     }
44 }

The Person class code in the above code provides 4 overloaded construction methods. If you have accurate name, age and date of birth information, you can use the construction method in line 15 of the code to create a Person object; if you only have name and age information, you can choose The construction method in line 21 of the code creates a Person object; if there is only name and date of birth information, the construction method in line 26 of the code can be used to create a Person object; if there is only name information, the construction method in line 32 of the code can be used to create a Person object.

Tips: If a constructor with parameters is added to the class, the system will not automatically generate a constructor with no parameters, so it is recommended to manually add a constructor with no parameters by default after adding a constructor with parameters.

Constructor encapsulation

Constructors can also be encapsulated, and the access level is the same as that of ordinary methods. For the access level of constructors, refer to [Java Learning Basics] Java Encapsulation and Access Control as shown in the figure. The sample code is as follows:

1  // Person.java file 
2  package com.a51work6;
 3  
4  import java.util.Date;
 5  
6  public  class Person {
 7  
8      // Name 
9      private String name;
 10      // Age 
11      private  int age;
 12      // Birth date 
13      private Date birthDate;
 14  
15      // Public level limit 
16      public Person(String n, int a, Date d) {        
 17         name = n;
 18          age = a;
 19          birthDate = d;
 20      }
 21  
22      // default level limit 
23      Person(String n, int a) {                       
 24          name = n;
 25          age = a;
 26      }
 27  
28      // protection Level Limit 
29      protected Person(String n, Date d) {            
 30          name = n;
 31          age = 30 ;
 32          birthDate =d;
 33      }
 34  
35      // private level limit 
36      ​​private Person(String n) {                      
 37          name = n;
 38          age = 30 ;
 39      }
 40  
41      ...
 42 }

Line 16 of the above code declares the public-level constructor. Line 23 of the code declares the default level, which can only be accessed within the same package. The 29th line of code is the constructor of the protection level, which is the same as the default level in the same package and can be inherited by subclasses in different packages. Line 36 of the code is a private-level constructor. This constructor can only be used in the current class and is not allowed to be accessed outside. The private constructor can be applied to designs such as the singleton design pattern .

----------------------------------------------------------------------------

Execution order of initialization blocks and constructors

Readers can read the following code by themselves to judge the output:

 1   class B extends Object
 2   {
 3       static
 4       {
 5           System.out.println("Load B");    
 6       }
 7       public B()
 8       {
 9             System.out.println("Create B");      
10      }
11  }    
12  class A extends B
13  {
14      static
15      {
16          System.out.println("Load A");
17      }
18      public A()
19      {
20          System.out.println("Create A");
21      }
22  }
23  
24  public class Testclass
25  {
26      public static void main(String [] args)
27      {
28          new A();
29      }
30  }

Output result:

Load B
Load A
Create B
Create A

      The initialization block is executed before the constructor is executed. In the class initialization stage, the static initialization block of the top-level parent class is executed first, and then executed in sequence, and finally the static initialization block of the current class is executed; when creating an object, the constructor of the top-level parent class is called first. , execute down in sequence, and finally call the constructor of this class. So the execution order is: parent class static code -> child class static code block -> parent class construction code block -> parent class constructor -> child class construction code block -> child class constructor

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653631&siteId=291194637