如何使子类型的对象访问父方法?

时间:2019-03-05 15:13:58

标签: java

我有以下超人类型的对象。我需要它两次调用一个方法,一次是从超人类,一次是从ActionCharacter -parent。该怎么做?

interface CanFight {void fight();}
interface CanFly {void fly();}
interface interface CanClimb{void climb();}
interface CanSwim{
     void swimFast();
     void treadH2O();
}
class ActionCharacter {
     public void fight() {System.out.println("fight an ActionChar");}
}
class Superman extends ActionCharacter implements CanFight, CanFly, CanClimb, CanSwim{
     String name = "Superman";
     public void fight() {System.out.println("fight bad guys");}
     public void fly() {System.out.println("fly faster than a bird");}  
     public void swimFast() {System.out.println("Swim faster than Michael Phelps");}
     public void treadH2O() {System.out.println("Tread water forever");}
     public void climb() {System.out.println("climb vertical cliffs");}
}
public class Action {
     public static void t(CanFight x) { x.fight(); }
     public static void v(CanFly x) { x.fly(); }
     public static void w(ActionCharacter x) { x.fight();}
     public static void x(CanClimb x) {x.climb();}
     public static void y(CanSwim x) {x.swimFast(); x.treadH2O();}

public static void main(String[] args) {
    Superman h = new Superman();
    System.out.println("I am " + h.name + " I can do the following:" );
    t(h); // Treat it as a CanFight
    y(h);
    v(h); // Treat it as a CanFly
    x(h);
    w(h); //This should print fight an ActionChar
    ActionCharacter i = (ActionCharacter)h;
    w(i); //Second attempt to print fight an ActionChar
}
}

2 个答案:

答案 0 :(得分:0)

在您的超类ActionCharacter中定义该方法,并在您的子类Superman中对其进行覆盖,因此两个对象(超人类型和ActionCharacter类型)都可以使用此方法

答案 1 :(得分:0)

java中的 super 关键字是一个引用变量,用于引用父类对象

在超人类中:

fight();

要从ActionCharacter父级进行调用:

super.fight();

super keyword