在Java中,子类构造方法会默认调用父类的无参构造方法。如果父类没有无参构造方法,那么子类必须显式地调用父类的有参构造方法。这可以通过使用super关键字来实现。
以下是两种调用父类构造方法的场景:
class Parent {
public Parent() {
System.out.println("Parent class constructor called");
}
}
class Child extends Parent {
public Child() {
// 隐式地调用父类的无参构造方法
super();
System.out.println("Child class constructor called");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
输出结果:
Parent class constructor called
Child class constructor called
class Parent {
public Parent(String message) {
System.out.println("Parent class constructor called with message: " + message);
}
}
class Child extends Parent {
public Child(String message) {
// 显式地调用父类的有参构造方法
super(message);
System.out.println("Child class constructor called");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child("Hello");
}
}
输出结果:
Parent class constructor called with message: Hello
Child class constructor called
在这两种情况下,super关键字用于调用父类的构造方法。在第一种情况下,由于父类有一个无参构造方法,所以super()可以省略,但为了清晰起见,建议保留。在第二种情况下,由于父类没有无参构造方法,所以必须使用super(message)来显式地调用父类的有参构造方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。