在Java编程中,构造函数是一个特殊的方法,用于创建和初始化对象。子类的构造函数是用来初始化子类对象的,它与父类的构造函数有着密切的关系。正确地使用子类构造函数是避免实例化过程中出现迷路问题的关键。
子类构造函数的作用
子类构造函数的主要作用是调用父类的构造函数,以便父类的对象也被正确初始化。如果不显式调用父类的构造函数,Java编译器会自动调用父类的不带参数的构造函数。
子类构造函数的调用
- 默认调用父类无参构造函数: 如果子类没有显式调用父类构造函数,编译器会自动调用父类的不带参数的构造函数。
class Parent {
Parent() {
System.out.println("Parent constructor called.");
}
}
class Child extends Parent {
Child() {
System.out.println("Child constructor called.");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
输出:
Parent constructor called.
Child constructor called.
- 显式调用父类构造函数: 如果需要调用父类的带参数的构造函数,可以在子类构造函数中显式调用。
class Parent {
Parent(String name) {
System.out.println("Parent constructor called with name: " + name);
}
}
class Child extends Parent {
Child(String name) {
super(name); // 显式调用父类带参数的构造函数
System.out.println("Child constructor called.");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child("John");
}
}
输出:
Parent constructor called with name: John
Child constructor called.
- 不能重复调用父类构造函数: 在子类构造函数中,只能调用一次父类构造函数,无论是显式调用还是隐式调用。
class Child extends Parent {
Child() {
super(); // 隐式调用
super(); // 重复调用父类构造函数,编译错误
System.out.println("Child constructor called.");
}
}
错误:
Child.java:6: error: The constructor Parent() is already called; cannot repeat
super();
^
Child.java:6: error: The constructor Parent() is already called; cannot repeat
super();
^ 1 error
实例化子类对象
在实例化子类对象时,子类构造函数会先调用父类构造函数,然后再执行子类构造函数中的代码。
class Main {
public static void main(String[] args) {
Child child = new Child("John");
}
}
在这个例子中,Child 构造函数会首先调用 Parent 构造函数,然后执行 Child 构造函数中的代码。
总结
学会Java子类构造函数的使用,可以帮助你更好地理解对象实例化过程中的父子关系。通过正确地调用父类构造函数,你可以确保父类和子类对象都被正确初始化。记住,在子类构造函数中只能调用一次父类构造函数,无论是显式调用还是隐式调用。这样,你就可以避免在实例化过程中迷路了。
