11.声明一个Shape抽象类,在此基础上派生出Rectangle和Circle类,二者都有GetArea( )函数计算对象的面积,

2025-01-31 07:54:49
推荐回答(1个)
回答1:

------------ Shape.java -------------
public abstract class Shape{
public abstract int getArea();
}
----------- Rectangle.java --------
public class Rectangle extends Shape{
int width;
int height;
public Rectangle(int width, height){ this.width=width; this.height=height;}
public int getArea() { return width*height;}
}
----------- Circle.java -------------
public class Circle extends Shape{
int r; //半径
public Circle(int r){ this.r = r; }
public int getArea() { return Math.PI * r * r; }
}
------------- Test.java -------------
public class Test{
public static void main(String[] args){
Shape rect = new Rectangle(20, 10);
System.out.println("Rectangle(20,10) area is: " + rect.getArea());
Shape circle = new Circle(5);
System.out.println("Circle(5) area is: " + circle.getArea());
}
}
满意请采纳!