类主要结构图
- 抽象类:Friend(朋友作为父类)
- 子类:Chinese(中国国籍)、Foreigner(外国国籍)
- 主人:Master(主人,用来款待客人)
- 测试类:FriendTest
类的方法图
- Friend:作为抽象类,属性(国籍、姓名)、方法(吃食物)
- Chinese:作为Friend的子类,展示自己独特的兴趣爱好(中国功夫)
- Foreigner:作为Friend的子类,展示自己独特的兴趣爱好(打橄榄球)
- Master:主人,作为招待客人,可以根据不同国籍的朋友提供对应的菜品
- FriendTest:测试类
代码示例
/**
* 测试类
*/
public class FriendTest {
public static void main(String[] args) {
Master master1 = new Master("张三");// 主人只会讲中文
Friend chinese = new Chinese("中国", "中国朋友");
master1.serving(chinese);
Master master2 = new Master("李四");// 主人精通各国语言
Friend foreigner = new Foreigner("外国", "外国朋友");
master2.serving(foreigner);
}
}
/**
* 主人类
*/
class Master {
private String name;// 主人姓名
public Master() { }
public Master(String name) { this.name = name; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
/**
* 陪客人,什么国籍的朋友用什么菜来招待
*/
public void serving(Friend friend) {
System.out.println(this.getName() + "陪" + friend.getName() + ":");
if (friend instanceof Chinese) {
Chinese chinese = (Chinese) friend;
chinese.eat("四川菜");
chinese.shadowboxing();
} else if (friend instanceof Foreigner) {
Foreigner foreigner = (Foreigner) friend;
foreigner.eat("比萨");
foreigner.hitFootball();
}
}
}
/**
* 朋友类,作为抽象类,提供一个共同方法eat
*
*/
abstract class Friend {
private String nationality; // 国籍
private String name; // 姓名
public String getNationality() { return nationality; }
public void setNationality(String nationality) { this.nationality = nationality; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Friend() {}
public Friend(String nationality, String name) {
this.nationality = nationality;
this.name = name;
}
/** 吃 */
public void eat(String food) {
System.out.println("吃" + food + "。");
}
}
/**
* 中国朋友,爱好练太极拳
*/
class Chinese extends Friend {
public Chinese(){ }
public Chinese(String nationality,String name){
super(nationality,name);
}
/** 练太极拳 */
public void shadowboxing(){
System.out.println("练太极拳!");
}
}
/**
* 外国朋友,爱好打橄榄球
*/
class Foreigner extends Friend {
public Foreigner(){ }
public Foreigner(String nationality,String name){
super(nationality,name);
}
/** 打橄榄球 */
public void hitFootball(){
System.out.println("打橄榄球!");
}
}
运行截图