定义抽象类Shape,圆形Circle、长方形Square、Rectangle为子类。
Shape类有一个数据成员(double型),定义带参构造方法、抽象方法calArea()(返回值类型:double)在Circle、Square两个类中,实现calArea()方法。在Rectangle类中,增加一个数据成员(double型),实现calArea()方法。编写测试类:定义一个Shape类引用shape,分别指向一个Circle类、Square类、Rectangle类对象,利用多态,计算各平面图形的面积并输出。(结果保留三位小数)要求:1.数据成员全部为私有成员;2.数据从键盘输入,调用带参构造方法创建子类对象。提示:使用Math类的PI
import java.util.Scanner;
public class ShapeDemo {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
double a,b,c,d;
a=in.nextDouble();
b=in.nextDouble();
c=in.nextDouble();
d=in.nextDouble();
Shape sh=new Circle(a);
System.out.printf("圆的面积:%.3f",sh.calArea());
System.out.println();
sh=new Square(b);
System.out.printf("正方形的面积:%.3f",sh.calArea());
System.out.println();
sh=new Rectangle(c,d);
System.out.printf("矩形的面积:%.3f",sh.calArea());
in.close();
}
}
abstract class Shape
{
private double a;
public Shape()
{
a=0;
}
public Shape(double a)
{
this.a=a;
}
abstract double calArea();
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
}
class Circle extends Shape
{
public Circle(double a)
{
super(a);
}
double calArea() {
return getA()*getA()*Math.PI;
}
}
class Square extends Shape
{
public Square(double a)
{
super(a);
}
double calArea() {
return getA()*getA();
}
}
class Rectangle extends Shape
{
private double b;
public Rectangle(double a,double b)
{
super(a);
this.b=b;
}
double calArea() {
return getA()*b;
}
}