📜  Java中的继承和构造函数

📅  最后修改于: 2022-05-13 01:57:59.215000             🧑  作者: Mango

Java中的继承和构造函数

在Java中,没有参数的基类构造函数在派生类构造函数中自动调用。例如,以下程序的输出是:
基类构造函数调用
调用派生类构造函数

Java
// filename: Main.java
class Base {
  Base() {
    System.out.println("Base Class Constructor Called ");
  }
}
 
class Derived extends Base {
  Derived() {
    System.out.println("Derived Class Constructor Called ");
  }
}
 
public class Main {
  public static void main(String[] args) { 
    Derived d = new Derived();
  }
}


Java
// filename: Main.java
class Base {
  int x;
  Base(int _x) {
    x = _x;
  }
}
 
class Derived extends Base {
  int y;
  Derived(int _x, int _y) {
    super(_x);
    y = _y;
  }
  void Display() {
    System.out.println("x = "+x+", y = "+y);
  }
}
 
public class Main {
  public static void main(String[] args) { 
    Derived d = new Derived(10, 20);
    d.Display();
  }
}


但是,如果我们想调用基类的参数化构造函数,那么我们可以使用 super() 来调用它。需要注意的是基类构造函数调用必须是派生类构造函数的第一行。例如,在下面的程序中,super(_x) 是第一行派生类构造函数。

Java

// filename: Main.java
class Base {
  int x;
  Base(int _x) {
    x = _x;
  }
}
 
class Derived extends Base {
  int y;
  Derived(int _x, int _y) {
    super(_x);
    y = _y;
  }
  void Display() {
    System.out.println("x = "+x+", y = "+y);
  }
}
 
public class Main {
  public static void main(String[] args) { 
    Derived d = new Derived(10, 20);
    d.Display();
  }
}