@[TOC](Structural methods to get started with Java)

What is a constructor

A class body has two types of members, one of which is a member method (the other is a member variable). Member methods are divided into two types, one is a normal member method, the other is a constructor (some sources also called constructors).

Constructors are the methods that are executed when the class is instantiated (when the object is created). In class declaration and instantiation, you already know how to instantiate an object:

Instantiate an object of class Football

The new keyword is used to instantiate the object, and the part after new is the constructor, which represents the constructor to call when new an object. Note that the new keyword can only be followed by a constructor, not a normal member method. So how do you distinguish a constructor from a plain member method? Keep reading.

The constructor does most of the initialization of the object (see code 1).

The form of the constructor method

Constructors are easy to identify. Constructors have the following characteristics:

The name of the method is the name of the class

Code 1:

public class Football{
    int size;
    String color;
    
    /* * Declare a constructor that takes no arguments; * Constructor name and class name are both Football; * The method body sets the initial value for the class member variable; * When instantiating any object, create an object with a size of 10 and a color of white; * After an object is instantiated, you can change the size and color values of the object members; * /
    public Football(a){
        size = 10;
        color = "white";
    }
    
    public void bounce(a){
        System.out.println("bang bang bang..."); }}Copy the code

The constructor has no return value type.

When you declare a constructor, you cannot add a type to the method. 2. There should be no similar return in the method. ; Statement like this. The following constructor declaration is incorrect, as shown in code 2:

Code 2:

public class Football{
    int size;
    String color;
    
    /* * error: can't precede a method with a method type int, can't return a value * but compilation passes because the compiler treats this method as a normal method declaration, not a constructor. * /
    public int Football(a){
        size = 10;
        color = "white";
        return 0;// Error, constructor cannot return data
    }
    
    public void bounce(a){
        System.out.println("bang bang bang..."); }}Copy the code

As you can see from the class name above, if you add a return value type to a constructor, the constructor is degraded to an ordinary member method and the compiler no longer treats it as a constructor.

Constructor usage points

1) Constructors are usually specified with the public type so that instances of classes can be created anywhere in the program.

2) Constructors can only be called when an object is instantiated, not from an object like normal methods.

Code 3:

public class AppMain{
    public static void main(String[] args){
        Football football1 = new Football();/ / right
        football1.bounce();/ / right
        football.Football();// Error, constructor cannot be called}}class Football{
    int size;
    String color;
    
    /* * error: can't precede a method with a method type int, can't return a value * but compilation passes because the compiler treats this method as a normal method declaration, not a constructor. * /
    public int Football(a){
        size = 10;
        color = "white";
        return 0;// Error, constructor cannot return data
    }
    
    public void bounce(a){
        System.out.println("bang bang bang..."); }}Copy the code

3) Each class has at least one constructor. If no constructor is written in the code, the Java system defaults to adding a constructor that takes no arguments and has no code in the method body. Such as:

Code 4:

public class Football {
    int size;
    String color;

    public void bounce(a) {
        System.out.println("I can jump: bang bang bang..."); }}Copy the code

The above code is equivalent to:

public class Football {
    int size;
    String color;
    
    // Construct method, no parameters, no method body
    public Football(a){}public void bounce(a) {
        System.out.println("I can jump: bang bang bang..."); }}Copy the code

4) Constructors cannot be modified by any non-access modifiers, such as static, final, synchronized, abstract, etc.

/* * error, stitac is a non-access modifier to modify */
public static class Football {
    int size;
    String color;
    
    // Construct method, no parameters, no method body
    public Football(a){}public void bounce(a) {
        System.out.println("I can jump: bang bang bang..."); }}Copy the code

5) Constructors can be overloaded.

Overloading is when methods in a class have the same name but different parameters. Note: Different numbers of parameters or different data types of parameters are counted as different parameters. In all other cases, the arguments are the same, and you can’t call it overloading.

/* * file: Football. Java * function: demo constructor overload */
public class Football {
    int size;
    String color;
    
    // When an instantiation operation constructs an object, the size and color parameters passed in are set to the member variables
    public Football(int sz,String clr){
        size = sz;
        color = clr;
    }

    /* Constructor overload * When an instantiation operation is performed to construct an object, * passes only the color argument, which is the default size 10. * therefore, all constructed objects are of size 10. */
    public Football(String clr){
        size = 10;
        color = clr;
    }
    
    public void bounce(a) {
        System.out.println("Size:" + size + ". Color:" 
                + color + ". I can jump: bang bang bang..."); }}Copy the code
 1 /* 2 * file: appmain.java 3 * function: test FootBall class, demo constructor overload 4 */
 5 public class AppMain {
 6 
 7     public static void main(String[] args) {
 8         // TODO Auto-generated method stub
 9         
10         /* 11 * The comment on line 15 below is an error, 12 * Because the Football class declared two constructors, 13 * So the Java system will not automatically add a constructor that takes no arguments 14 */
15         //Football football1 = new Football();
16         
17         Football football1 = new Football(18."Black");
18         Football football2 = new Football(12."White");
19         
20         football1.bounce();
21         football2.bounce();
22     }
23 
24 }
Copy the code

Learning test:

  1. Which of the following Sample classes is not a constructor, which is a constructor with arguments, and which is a constructor with no arguments:
public class Sample {  
      
    private int x;  
  
    public Sample(a) { 
        this(1);  
    }  
      
    public Sample(int x) { 
        this.x=x;  
    }  
      
    public int Sample(int x) { 
        returnx++; }}Copy the code
  1. What is the output result of the following code
public class Mystery {  
    private String s;  
      
    public void Mystery(a) { 
       s = "constructor";  
    }  
      
    void go(a) {  
       System.out.println(s);  
    }  
      
    public static void main(String[] args) {  
       Mystery m = newMystery(); m.go(); }}Copy the code

3. What is the output result of the following code?

A. ava:

public class A{
   public A(a){
      System.out.println("Call the constructor without arguments");
   }
   public A(String mess){
      System.out.println("Constructor \n with arguments called"+
         "Parameter content is:"+mess); }}Copy the code

Test.java:


public class Test{  
   public static void main(String [] args){  
       A a_1=new A();// Call the constructor with no arguments
       A a_2=new A("Hello");// Call the constructor with arguments}}Copy the code

[Information Kit]