首页 > 解决方案 > 如何使子类型的对象访问父方法?

问题描述

我有以下超人类型的对象。我需要它调用一个方法两次,一次来自 Superman 类,一次来自 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
}
}

标签: java

解决方案


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


推荐阅读