Home  >  Article  >  Java  >  Explanation of Java base class constructor calling (with code)

Explanation of Java base class constructor calling (with code)

不言
不言forward
2018-10-08 15:03:412444browse

This article brings you an explanation of Java base class constructor calling (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There is such a passage in Chapter 7 of "Java Programming Thoughts" on reusable classes, which is worth pondering. When a subclass inherits a parent class, it involves two classes: the base class and the derived class (subclass). From the outside, a derived class looks like a new class with the same interface as the base class, perhaps with some additional methods and fields. But inheritance doesn't just copy the base class's interface. When you create an exported class object, the object contains a sub-object of the base class. This sub-object is the same as the object you create directly with the base class. The difference between the two is that the latter comes from the outside, while the sub-object of the base class Sub-objects are wrapped inside derived class objects.

This raises a very important issue. The correct initialization of the base class sub-object is also crucial (we may use the methods and fields inherited from the base class in the sub-class), and also There is only one way to ensure this: call the base class constructor in the subclass constructor to perform initialization.

Parameterless base class constructor

We know that when you do not give it a constructor for a class, Java will automatically call the parameterless constructor for you, and Java will also export it. Insert a call to the base class constructor into the class constructor. The following code illustrates this working mechanism:

//: reusing/Cartoon.java
// Constructor calls during inheritance.
import static net.mindview.util.Print.*;

class Art {
  Art() { print("Art constructor"); }
}

class Drawing extends Art {
  Drawing() { print("Drawing constructor"); }
}

public class Cartoon extends Drawing {
  public Cartoon() { print("Cartoon constructor"); }
  public static void main(String[] args) {
    Cartoon x = new Cartoon();
  }
} /* Output:
Art constructor
Drawing constructor
Cartoon constructor
*///:~

Observe the running results of the above code. When creating a Cartoon object, the constructor of its parent class Drawing will first be called, and its parent class inherits from the Art class. So the constructor of the Art class will be called again, just like layer by layer. Although its parent class constructor is not explicitly called in its constructor, Java will automatically call the constructor of its parent class. Even if you don't create a constructor for Cartoon(), the compiler will synthesize a default no-argument constructor that will call the base class's constructor.

Base class constructor with parameters

When the constructor in the base class all has parameters, the compiler will not call it automatically and must be called explicitly using the keyword super Base class constructor, and pass in the appropriate parameters. The corresponding example code is as follows:

//: reusing/Chess.java
// Inheritance, constructors and arguments.
import static net.mindview.util.Print.*;

class Game {
  Game(int i) {
    print("Game constructor");
  }
}

class BoardGame extends Game {
  BoardGame(int i) {
    super(i);
    print("BoardGame constructor");
  }
}   

public class Chess extends BoardGame {
  Chess() {
    super(11);
    print("Chess constructor");
  }
  public static void main(String[] args) {
    Chess x = new Chess();
  }
} /* Output:
Game constructor
BoardGame constructor
Chess constructor
*///:~

As can be observed from the above code, the parent class constructor must be called using super explicitly in the subclass Chess constructor. and pass in the appropriate parameters. Furthermore, calling the base class constructor must be the first thing done in the subclass constructor.

The calling sequence issue of the base class constructor

Before that, let’s first discuss the initialization issue of object reference. In Java, fields in a class can be automatically initialized to zero when they are basic types, but object references will be initialized to null. We often need to initialize it at the appropriate location. Here are several locations where initialization can be performed:

1. Where the object is defined. This means that they can always be initialized before the constructor is called.

2. In the constructor of the class.

3. Just before these objects are used, this method is called lazy initialization.

Remember point 1 above, let’s look at a more complex example to look at the calling sequence of the base class constructor.

// reusing/Ex7/C7.java
// TIJ4 Chapter Reusing, Exercise 7, page 246
/* Modify Exercise 5 so that A and B have constructors with arguments instead
* of default constructors. Write a constructor for C and perform all 
* initialization within C's constructor. 
*/
 
import static org.greggordon.tools.Print.*;

class A { 
    A(char c, int i) { println("A(char, int)");} 
}

class B extends A {     
    B(String s, float f){
        super(' ', 0); 
        println("B(String, float)");
    } 
}

class C7 extends A { 
    private char c;
    private int i;
    C7(char a, int j) {     
        super(a, j); 
        c = a;
        i = j;
    }
    B b = new B("hi", 1f); // will then construct another A and then a B
    public static void main(String[] args) {
        C7 c = new C7('b', 2); // will construct an A first
    }
}

The above code output:

A(char, int)

A(char, int)

B(String, float)

Pay attention to the order of base class constructor, subclass constructor, and class member object initialization:

1. When new an object of a class, first call its parent class constructor (can be parameterless or parameterized, the system will automatically call the parameterless one, and you need to specify it yourself if there are parameters). Such as super(a, j)

2 in C7 above. Then execute its member object initialization statement and call the constructor of class B, such as
B b = new B("hi", 1f) above, and the constructor of B will first call the constructor of base class A.

3. Finally, return to the constructor in C7 and continue executing c=a,i=j.

The above is the detailed content of Explanation of Java base class constructor calling (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete