java - 如何使子类型的对象访问父方法?
问题描述
我有以下超人类型的对象。我需要它调用一个方法两次,一次来自 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
}
}
解决方案
在您的超类中定义该方法ActionCharacter
并在您的子类中覆盖它Superman
,因此两个对象(超人类型和 ActionCharacter 类型)都可以使用此方法
推荐阅读
- html - 从模板中删除轮廓并将其扩展为 100%
- javascript - 在按钮单击时禁用模式输入
- amazon-web-services - AWS Serverless 图像处理程序是否存储衍生品?
- python - Kivy:我可以自由改变按钮内文本的位置吗?并在按钮中添加另一个文本?
- python - MRO,超级如何在 python 中工作
- ios - 无法将数据填充到表视图中
- python - Python:沿边界从图像中裁剪区域
- java - 带有 Gradle 的 SpringBoot 应用程序因 ./gradlew bootRun 而失败
- r - R:从主题 ID 创建新的聚类变量
- python - Python Telegram bot 从列表中添加处理程序