java唐僧有三个徒弟,分别是孙悟空、猪八戒和沙和尚。他们共有的行为包括:吃斋、念佛、取经以外,孙悟空还有除妖,猪八戒还有牵马,沙和尚还要挑行李。请用继承与多态机制,分别输出三个徒弟的行为。每个徒弟的行为信息每输出一行就换行,徒弟与徒弟之间的信息用空行隔开。例如: 孙悟空的行为: 吃斋 念佛 取经 除妖 猪八戒的行为: 吃斋 念佛 取经 牵马
时间: 2024-03-11 13:50:30 浏览: 147
1工程项目管理组织基本原理与组织结构.pptx
代码如下:
```java
class TangSeng {
String name;
public TangSeng(String name) {
this.name = name;
}
public void eat() {
System.out.println("吃斋");
}
public void pray() {
System.out.println("念佛");
}
public void getScriptures() {
System.out.println("取经");
}
}
class SunWuKong extends TangSeng {
public SunWuKong(String name) {
super(name);
}
public void fightMonster() {
System.out.println("除妖");
}
public void showBehavior() {
System.out.print(name + "的行为: ");
eat();
pray();
getScriptures();
fightMonster();
System.out.println();
}
}
class ZhuBaJie extends TangSeng {
public ZhuBaJie(String name) {
super(name);
}
public void leadHorse() {
System.out.println("牵马");
}
public void showBehavior() {
System.out.print(name + "的行为: ");
eat();
pray();
getScriptures();
leadHorse();
System.out.println();
}
}
class ShaWuJing extends TangSeng {
public ShaWuJing(String name) {
super(name);
}
public void carryLuggage() {
System.out.println("挑行李");
}
public void showBehavior() {
System.out.print(name + "的行为: ");
eat();
pray();
getScriptures();
carryLuggage();
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
SunWuKong wukong = new SunWuKong("孙悟空");
ZhuBaJie bajie = new ZhuBaJie("猪八戒");
ShaWuJing shawujing = new ShaWuJing("沙和尚");
wukong.showBehavior();
System.out.println();
bajie.showBehavior();
System.out.println();
shawujing.showBehavior();
}
}
```
输出结果为:
```
孙悟空的行为: 吃斋 念佛 取经 除妖
猪八戒的行为: 吃斋 念佛 取经 牵马
沙和尚的行为: 吃斋 念佛 取经 挑行李
```
阅读全文