13初级 - 面向对象:多态-练习

228 阅读2分钟

13

1

  • main.java
package com.github.hcsp.polymorphism;

public class Main {
    // 实现一个"形状"的继承体系:
    // 形状Shape为父类
    // 正方形Square、长方形Rectangle、圆Circle为子类
    // 子类覆盖父类求面积的多态方法getArea()
    public static void main(String[] args) {
        Shape[] shapes = new Shape[]{new Square(1.0), new Rectangle(1.0, 2.0), new Circle(1.0)};
        for (Shape shape : shapes) {
            System.out.println("" + shape.getClass().getSimpleName() + "的面积是:" + shape.getArea());
        }
    }
}
  • shape.java
package com.github.hcsp.polymorphism;

public class Shape {
    // 返回当前"形状"(Shape)的面积
    public double getArea() {
        return 0d;
    }
}
  • square.java
package com.github.hcsp.polymorphism;

public class Square extends Shape {
    // 正方形的边长
    private double sideLength;

    public Square(double sideLength) {
        this.sideLength = sideLength;
    }

    public double getArea() {
        return sideLength * sideLength;
    }
}

2

  • main.java,多态只发生在消息接受方,不发生在参数,参数看哪个类型范围大第一个匹配
package com.github.hcsp.polymorphism;

public class Main {
    // 猜一下输出结果是什么,然后运行一下看看是不是和你预期相符
    // 请修改下面的代码,使之输出
    // "I am Sub, the param is ParamSub"
    public static void main(String[] args) {
        Base object = new Sub();
        ParamSub param = new ParamSub();
        object.print(param);
    }
}
  • base.java
package com.github.hcsp.polymorphism;

public class Base {
    public void print(ParamBase param) {
        System.out.println("I am Base, the param is ParamBase");
    }

    public void print(ParamSub param) {
        System.out.println("I am Base, the param is ParamSub");
    }
}
  • sub.java
package com.github.hcsp.polymorphism;

public class Sub extends Base {
    @Override
    public void print(ParamBase param) {
        System.out.println("I am Sub, the param is ParamBase");
    }

    @Override
    public void print(ParamSub param) {
        System.out.println("I am Sub, the param is ParamSub");
    }
}
  • paramBase.java
package com.github.hcsp.polymorphism;

public class ParamBase {}
  • paramSub.java
package com.github.hcsp.polymorphism;

public class ParamSub extends ParamBase {}

3

  • main.java
package com.github.hcsp.polymorphism;

public class Main {
    // 请仔细观察`西红柿炒鸡蛋`/`清炒菜心`/`煎鸡蛋`几个类
    // 提取他们的公共代码到`菜`中,完成重构
    // 注意不要修改各个菜的烹饪步骤
    public static void main(String[] args) {
        菜[] 菜们 = new 菜[] {new 西红柿炒鸡蛋(), new 清炒菜心(), new 煎牛排()};
        for (菜 一个菜 : 菜们) {
            一个菜.做一个菜();
        }
    }
}
  • 菜.java
package com.github.hcsp.polymorphism;

public class 菜 {


    public void 做一个菜() {
        洗锅();
        倒油();
        开始烹饪();
        放佐料();
        出锅();
    }

    public void 洗锅() {
        System.out.println("洗炒锅");
    }

    public void 倒油() {
        System.out.println("倒油");
    }

    public void 开始烹饪() {
    }

    public void 放佐料() {
        System.out.println("放盐");
    }

    public void 出锅() {
    }
}
  • 清炒菜心.java
package com.github.hcsp.polymorphism;

public class 清炒菜心 extends 菜 {
    @Override
    public void 倒油() {
        System.out.println("倒一点点油");
    }

    @Override
    public void 开始烹饪() {
        System.out.println("放青菜");
        System.out.println("炒啊炒啊炒");
    }

    @Override
    public void 放佐料() {
        System.out.println("放酱油");
        super.放佐料();
    }

    @Override
    public void 出锅() {
        System.out.println("香喷喷的清炒菜心出锅啦");
    }
}

4

  • PriceCalculator.java
package com.github.hcsp.polymorphism;

public class PriceCalculator {
    // 使用策略模式重构这个方法,实现三个策略:
    // NoDiscountStrategy 不打折
    // Discount95Strategy 全场95折
    // OnlyVipDiscountStrategy 只有VIP打95折,其他人保持原价
    // 重构后的方法签名:
    // public static int calculatePrice(DiscountStrategy strategy, int price, User user)

    public static int calculatePrice(DiscountStrategy strategy, int price, User user) {
        return strategy.discount(price, user);
    }


//    public static int calculatePrice(String discountStrategy, int price, User user) {
//        switch (discountStrategy) {
//            case "NoDiscount":
//                return price;
//            case "Discount95":
//                return (int) (price * 0.95);
//            case "OnlyVip": {
//                if (user.isVip()) {
//                    return (int) (price * 0.95);
//                } else {
//                    return price;
//                }
//            }
//            default:
//                throw new IllegalStateException("Should not be here!");
//        }
//    }
}
  • DiscountStrategy.java
package com.github.hcsp.polymorphism;

public class DiscountStrategy {
    public int discount(int price, User user) {
        throw new UnsupportedOperationException();
    }
}
  • Discount95Strategy.java
package com.github.hcsp.polymorphism;

public class Discount95Strategy extends DiscountStrategy {
    @Override
    public int discount(int price, User user) {
        return price * 95 / 100;
    }
}