Java中的继承和构造函数

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

null

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();
}
}


但是,如果我们想调用基类的参数化构造函数,那么我们可以使用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();
}
}


输出: x=10,y=20 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享