第十周作业

package lianxi1;
/*2、设计四个类,分别是:(知识点:抽象类及抽象方法)
(1)Shape表示图形类,有面积属性area、周长属性per,颜色属性color,有两个构造方法(一个是默认的、一个是为颜色赋值的),还有3个抽象方法,分别是:getArea计算面积、getPer计算周长、showAll输出所有信息,还有一个求颜色的方法getColor。

 */
public abstract class Shape {
    protected double area;
    protected double per;
    protected String color;
    public Shape() {
    }

    public Shape(String color) {
        this.color = color;
    }
     public abstract void getArea();

     public abstract void getPer();

     public abstract void showAll();
        
}
package lianxi1;
/*(2)2个子类:
1)Rectangle表示矩形类,增加两个属性,Width表示长度、height表示宽度,重写getPer、getArea和showAll三个方法,另外又增加一个构造方法(一个是默认的、一个是为高度、宽度、颜色赋值的)。
*/
public class Rectangle extends Shape{
        double width;
        double height;
        public Rectangle() {
        }
        public Rectangle(String color, double width, double height) {
            super(color);
            this.width = width;
            this.height = height;
            this.color=color;
        }
        public void getPer() {
            per = (width+height)*2;
        }
        public void getArea() {
            area =(width*height);
        }
        public void showAll() {
            System.out.println("矩形面积为:" + area + ",周长为:" + per + ",颜色:" + color);
        }
}
package lianxi1;
/*2)Circle表示圆类,增加1个属性,radius表示半径,重写getPer、getArea和showAll三个方法,另外又增加两个构造方法(为半径、颜色赋值的)。*/
public class Circle extends Shape{
    int radius;

    public Circle(int radius,String color) {
        super(color);
        this.radius = radius;
        this.color=color;
    }

    public void getPer() {
        per = radius*2*3.14;
    }
    public void getArea() {
        area =radius*radius*3.14;
    }
    public void showAll() {
        System.out.println("圆形面积为:" + area + ",周长为:" + per + ",颜色:" + color);
    }
    
}
package lianxi1;
/*(3)一个测试类PolyDemo,在main方法中,声明创建每个子类的对象,并调用2个子类的showAll方法。*/
public class Polydamo {
    public static void main(String[] args) {
        Shape r1= new Rectangle("蓝色",5.0,6.0);
        Shape c1 = new Circle(5,"白色");
        r1.getArea();
        r1.getPer();
        c1.getArea();
        c1.getPer();
        r1.showAll();
        c1.showAll();
    }
}

原文地址:https://www.cnblogs.com/2399301032wr/p/12929758.html