java如何调用继承
调用继承的方法
在Java中,继承允许子类调用父类的方法和属性。通过继承机制,子类可以重用父类的代码,并根据需要扩展或修改父类的行为。
子类可以直接调用继承自父类的非私有方法。如果父类的方法未被覆盖(override),子类实例将直接使用父类的方法实现。

class Parent {
void display() {
System.out.println("Parent's display method");
}
}
class Child extends Parent {
// 直接继承Parent的display方法
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display(); // 调用继承自Parent的display方法
}
}
使用super关键字调用父类方法
当子类覆盖父类方法时,可以使用super关键字显式调用父类的方法。super提供了一种访问父类成员的方式。
class Parent {
void display() {
System.out.println("Parent's display method");
}
}
class Child extends Parent {
@Override
void display() {
super.display(); // 调用父类的display方法
System.out.println("Child's display method");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display(); // 先调用Parent的display,再执行Child的display
}
}
调用父类的构造方法
子类构造方法可以通过super()调用父类的构造方法。如果父类构造方法需要参数,子类必须通过super传递相应参数。

class Parent {
Parent(String message) {
System.out.println("Parent constructor: " + message);
}
}
class Child extends Parent {
Child() {
super("Hello from Child"); // 调用父类构造方法
System.out.println("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
方法重写与调用
当子类重写父类方法时,子类对象将调用子类的方法实现。如果需要在子类中访问父类被重写的方法,必须使用super关键字。
class Parent {
void show() {
System.out.println("Parent's show");
}
}
class Child extends Parent {
@Override
void show() {
System.out.println("Child's show");
}
void callParentShow() {
super.show(); // 调用父类被重写的show方法
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.show(); // 调用Child的show
child.callParentShow(); // 调用Parent的show
}
}
多级继承中的方法调用
在多级继承中,子类可以调用任意上级父类的方法,只要这些方法未被中间类重写。使用super只能直接访问上一级父类的方法。
class Grandparent {
void print() {
System.out.println("Grandparent's print");
}
}
class Parent extends Grandparent {
@Override
void print() {
System.out.println("Parent's print");
}
}
class Child extends Parent {
void callGrandparentPrint() {
super.super.print(); // 语法错误,不能跳过父级
// 正确方式是在Parent类中添加访问Grandparent的方法
}
}
对于多级继承,通常需要在中间类中添加辅助方法才能访问更上层的方法。






