多态 继承 封装 打印输出长方形 正方形 圆形的周长和面积

三个类皆有自己计算周长 面积的方法
正方形是特殊的矩形
图形是他们共同的父类

public class TestShape {
	public static void main(String[] args){
		Shape[] s = new Shape[3];
		s[0] = new Circle(10);
		s[1] = new Rect(2,6);
		s[2] = new Square(3);
		System.out.println("圆的面积为:"+s[0].cals());
		System.out.println("圆的周长为:"+s[0].calc());
		
		
		System.out.println("长方形的面积为:"+s[1].cals());
		System.out.println("长方形的周长为:"+s[1].calc());
		
		
		System.out.println("正方形的面积为:"+s[2].cals());
		System.out.println("正方形的周长为:"+s[2].calc());
	}
}


class Shape {
   //计算面积
	public double cals(){
	    return 0.0;
    }

   //计算周长
    public double calc(){
	    return 0.0;
    }
}

//长方形类
class Rect extends  Shape{
    private double l;
    private double s;
    public Rect(){}
    public Rect(double l, double s) {
        this.l = l;
        this.s = s;
    }

    public double getL() {
        return l;
    }

    public void setL(double l) {
        this.l = l;
    }

    public double getS() {
        return s;
    }

    public void setS(double s) {
       this.s = s;
    }

    public double cals() {
       return s*l;
    }

    public double calc() {
       return 2*(s+l);
    } 

}
//正方形
class Square extends Rect{
	public Square (double s){
		super.setS(s);
	}


	public double cals() {
		super.getS();
	    return getS()*getS();
	}

	public double calc() {
	    return 4*getS();
	}
}


//圆形
class Circle extends Shape{

     private double r;

     public Circle(double r) {
         this.r = r;
     }

     public double getR() {
         return r;
     }

     public void setR(double r) {
         this.r = r;
     }

     public double cals() {
         return Math.PI*r*r;
     }

     
     public double calc() {
         return 2*Math.PI*r;
     }
 }在这里插入代码片

你可能感兴趣的:(多态 继承 封装 打印输出长方形 正方形 圆形的周长和面积)