13
1
package com.github.hcsp.polymorphism;
public class Main {
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());
}
}
}
package com.github.hcsp.polymorphism;
public class Shape {
public double getArea() {
return 0d;
}
}
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 {
public static void main(String[] args) {
Base object = new Sub();
ParamSub param = new ParamSub();
object.print(param);
}
}
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");
}
}
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");
}
}
package com.github.hcsp.polymorphism;
public class ParamBase {}
package com.github.hcsp.polymorphism;
public class ParamSub extends ParamBase {}
3
package com.github.hcsp.polymorphism;
public class Main {
public static void main(String[] args) {
菜[] 菜们 = new 菜[] {new 西红柿炒鸡蛋(), new 清炒菜心(), new 煎牛排()};
for (菜 一个菜 : 菜们) {
一个菜.做一个菜();
}
}
}
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 出锅() {
}
}
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
package com.github.hcsp.polymorphism;
public class PriceCalculator {
public static int calculatePrice(DiscountStrategy strategy, int price, User user) {
return strategy.discount(price, user);
}
}
package com.github.hcsp.polymorphism;
public class DiscountStrategy {
public int discount(int price, User user) {
throw new UnsupportedOperationException();
}
}
package com.github.hcsp.polymorphism;
public class Discount95Strategy extends DiscountStrategy {
@Override
public int discount(int price, User user) {
return price * 95 / 100;
}
}