Java多态

描述

运用 Java 多态,设计男女朋友

题目

运用 Java 多态,设计男女朋友相关类,类的关系如下:

人类:

​ 属性:名字、身高。

女朋友类:

​ 属性:名字、身高。

​ 行为:煮饭、洗衣服。

男朋友类:

​ 属性:名字、身高。

​ 行为:赚钱、陪女朋友逛街。

衣服类:

​ 属性:颜色、品牌。

题目解决思路

  1. 创建人类。
  2. 女朋友类继承人类,实现特有煮饭、洗衣服方法。
  3. 男朋友类继承人类,实现特有赚钱、陪女朋友逛街方法。
  4. 创建衣服类。

代码具体实现

人类代码:

public class People { private String name; private int stature; // 无参构造 public People() { } // 全参构造 public People(String name, int stature) { this.name = name; this.stature = stature; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStature() { return stature; } public void setStature(int stature) { this.stature = stature; } }

女朋友类代码:

public class GirlFriend extends People { // 无参构造 public GirlFriend() { } // 全参构造 public GirlFriend(String name, int stature) { super(name, stature); } // 煮饭方法 public void cook(){ System.out.println(super.getName() + "正在煮饭"); } // 洗衣服方法 public void laundry(Clothes clothes){ System.out.println(super.getName() + "正在洗" + clothes.getColor() + "的" + clothes.getBrand() + "衣服"); } }

男朋友类代码:

public class BoyFriend extends People{ // 无参构造 public BoyFriend() { } // 全参构造 public BoyFriend(String name, int stature) { super(name, stature); } // 赚钱方法 public void makeMoney(){ System.out.println(super.getName() + "正在赚钱"); } // 陪女朋友逛街方法 public void doShopping(GirlFriend girlFriend){ System.out.println(super.getName()+ "正在陪" + girlFriend.getName() + "逛街"); } }

衣服类代码:

public class Clothes { private String brand; private String color; // 无参构造 public Clothes() { } // 全参构造 public Clothes(String brand, String color) { this.brand = brand; this.color = color; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }

测试类代码:

public class Test { public static void main(String[] args) { System.out.println("嗨客网(www.haicoder.net)\n"); // 女朋友类 People people1 = new GirlFriend("珍妮",20); Clothes clo = new Clothes("NIKE","红色"); GirlFriend gf = (GirlFriend) people1; gf.cook(); gf.laundry(clo); // 男朋友类 People people2 = new BoyFriend("汤姆",22); BoyFriend bf = (BoyFriend) people2; bf.makeMoney(); bf.doShopping(gf); } }

运行结果如下图:

04_java多态.png

以上案例,运用 Java 多态,设计男女朋友相关类。