Java如何调用父类的父类方法
在Java中,子类继承父类时,可以通过关键字super
调用父类的方法或属性。但是,如果想要调用父类的父类的方法,就需要使用一些特殊的方法。
方法一:通过super
关键字多次调用父类的方法
当需要调用父类的父类方法时,可以通过多次使用super
关键字来实现。以下是一个示例代码:
class GrandParent {
public void method() {
System.out.println("GrandParent's method");
}
}
class Parent extends GrandParent {
@Override
public void method() {
super.method();
System.out.println("Parent's method");
}
}
class Child extends Parent {
@Override
public void method() {
super.method(); // 调用父类的方法
System.out.println("Child's method");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.method();
}
}
输出结果为:
GrandParent's method
Parent's method
Child's method
在上面的代码中,Child
类继承了Parent
类,而Parent
类又继承了GrandParent
类。通过在子类的方法中使用super
关键字多次调用父类的方法,可以实现调用父类的父类的方法。
方法二:通过递归调用父类的方法
另一种方法是通过递归调用父类的方法来实现调用父类的父类的方法。以下是一个示例代码:
class GrandParent {
public void method() {
System.out.println("GrandParent's method");
}
}
class Parent extends GrandParent {
@Override
public void method() {
super.method();
System.out.println("Parent's method");
}
}
class Child extends Parent {
@Override
public void method() {
super.method();
System.out.println("Child's method");
}
public void callGrandParentMethod() {
super.method(); // 递归调用父类的方法
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.callGrandParentMethod();
}
}
输出结果为:
GrandParent's method
Parent's method
GrandParent's method
在上面的代码中,Child
类通过递归调用父类的方法来实现调用父类的父类的方法。在callGrandParentMethod()
方法中,通过super.method()
调用Parent
类的方法,而在Parent
类的方法中,又通过super.method()
调用GrandParent
类的方法。
注意事项
在使用以上两种方法时,需要注意以下几点:
-
如果父类的方法是私有的(
private
),则不能通过以上方法调用。私有方法只能在本类中使用。 -
如果父类的方法是静态的(
static
),则不能通过以上方法调用。静态方法是属于类的,而不是实例的。 -
如果父类的方法是被子类覆盖的(
@Override
),则调用的是子类覆盖后的方法,而不是父类的方法。如果想要调用父类的方法,可以使用以上方法中的任意一种。
总结
Java中可以通过关键字super
来调用父类的方法,通过多次使用super
关键字或者递归调用父类的方法,可以实现调用父类的父类的方法。但需要注意私有方法和静态方法的调用方式。