Second, Java object-oriented (4) _ constructor

2018-04-29

 

Constructor (Constructor/Constructor)

 

In a java class, if you do not explicitly declare a constructor, the JVM will give the class a no-argument default (default) constructor that executes no code (that is, no method body in curly braces) and you generate the class Only methods with no parameters can be used for the object. A class can have multiple constructors ( overloading ). A class has at least one constructor
When a class declares a constructor, the JVM will not assign a default constructor to the class. Therefore, if you write a constructor with parameters, it is better to add a constructor without parameters. 

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

First, the role of the constructor

  • To create an object of a class, it must be used together with the new keyword (creating an object is actually calling the constructor, the constructor cannot be called directly, and must be used together with new ).
  • Initialize (instantiate) an object

 

Second, the characteristics of the constructor

  • The method name of the constructor must be the same as the class name.
  • Constructors have no return type (so no return type is declared before the method name) and cannot be defined as void. void Student(){}; This is normal method.
  • The return statement does not need to be used in the constructor. ( In fact, the constructor has a return value, which returns a reference to the currently created object ).
  • Constructors can be overloaded.

 

3. Default (default) constructor

  • Conforms to the characteristics of the constructor
  • no parameters
  • no method body
  • If class A is not decorated with public, then the default constructor also has no public modifier

   If class A uses the public modifier, then the default constructor also uses the public modifier

   (In general, the default constructor is consistent with the access modifier of the current class)

 

Code description:

1 public class Test3 {
 2    private int n;
 3
 4 Test3() {
 5 System.out.println("Call the default constructor");
 6    }
 7
 8    Test3(int n) {
 9       this.n = n;
10 System.out.println("Call non-default constructor");
11   }
12
13    public static void main(String[] args) {
14 Test3 t1; //Declare an object without calling any constructor (no initialization)
15 Test3 t2 = new Test3(); //declare and create an object using the default constructor
16 Test3 t3 = new Test3(3); //declare and create an object with a non-default constructor without a default constructor
17    }
18 }

 

 

Fourth, the overloading of the constructor

  A constructor is a special method that can be overloaded.

 

Guess you like

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