首页 > 其他 > 详细

面向对象案例 - 多态,继承

时间:2020-05-04 12:15:53      阅读:51      评论:0      收藏:0      [点我收藏+]

1.求矩形、正方形和圆形的面积与周长

技术分享图片

 

 

package randi;
import static java.lang.Math.PI;
public class ShapeDemo {

    public static void main(String[] args) {

        Shape sha = new Shape();
        
        Circle s1 = new Circle(10);
        Rect s2 = new Rect(5, 6);
        Squr s3 = new Squr(10);
        
        sha.print(s1);
        sha.print(s2);
        sha.print(s3);
    }
}

class Shape {
    
    public void print(Shape sha) {
        System.out.println(sha.getName() + "面积: " + sha.getArea());
        System.out.println(sha.getName() + "周长: " + sha.getGirth());
    }

    public double getArea() {
        return 0;
    }

    public double getGirth() {
        return 0;
    }
    
    public String getName() {
        return null;
    }
}


class Circle extends Shape {
    private double radius;
    
    public Circle() {}
    public Circle(double radius) {
        this.radius = radius;
    }

    public double getArea() {
        return PI * radius * radius;
    }

    public double getGirth() {
        return PI * radius * 2;
    }

    public String getName() {
        return "Cir";
    }
}

class Rect extends Shape {
    private double length;
    private double width;
    
    public Rect() {}
    public Rect(double length, double width) {
        this.length = length;
        this.width = width;
    }

    public double getArea() {
        return width * length;
    }

    public double getGirth() {
        return (width + length) * 2;
    }

    public String getName() {
        return "Rect";
    }
}

class Squr extends Rect {
    
    public Squr() {}
    public Squr(double length) {
        super(length, length);

    }

    public String getName() {
        return "Squr";
    }
}


 

面向对象案例 - 多态,继承

原文:https://www.cnblogs.com/raising/p/12825837.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!