题目
1.定义一个抽象类Shape,包含属性:name、color、抽象方法area(),非抽象方法display。
2.定义一个Circle类,继承Shape类,包含一个双精度类型实例变量radius,以及一个构造方法,该方法使用super关键字调用父类Shape的构造方法,来初始化color和name。Circle类还实现了抽象方法area(),用于计算圆形面积。
3.定义一个常量类,常量类中定义一个常量用来专门储存圆周率
4.定义一个Rectangle类,继承Shape类,包含两个双精度类型实例变量width和height,以及一个构造方法,该方法使用super关键字调用父类Shape的构造方法,来初始化color和name。Rectangle类还实现了抽象方法area(),用于计算矩形面积。
5.在程序的main方法中,创建一个Circle对象,和一个Rectangle对象,并分别调用它们的display()方法,输出结果。调用area()方法输出面积。
代码如下
//形状类(抽象类)
public abstract class Shape {
private String name;
private String color;
public Shape() {
}
public Shape(String name, String color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
/*
计算图形面积的抽象方法,因为在父类中不能确定具体是什么图形,
因此该方法无法在Shape类中实现,只能到子类中实现。
*/
public abstract double area();
/*
显示图形的信息。
*/
public void display(){
System.out.println(this.getName() + "的颜色是:" + this.getColor());
}
}
//圆形类。
public class Circle extends Shape{
private double radius;
public Circle(){
}
@Override
public double area() {
return Constant.MATH_PI * this.radius * this.radius;
}
public Circle(String name,String color,double radius){
super(name, color);
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
//常量类,专门用来存储常量。
public class Constant {
//数学中的圆周率。
public static final double MATH_PI = 3.14;
}
//长方形类。
public class Rectangle extends Shape{
private double width;
private double height;
public Rectangle(){
}
@Override
public double area() {
return this.getHeight() * this.getWidth();
}
public Rectangle(String name,String color,double width,double height){
super(name, color);
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
public class Test {
public static void main(String[] args) {
//创建圆形对象
Circle circle = new Circle("圆形","蓝色",3.0);
circle.display();
System.out.println(circle.getName() + "面积是:" + circle.area());
//创建长方形对象
Rectangle rectangle = new Rectangle("长方形","粉色",2.0,3.0);
rectangle.display();
System.out.println(rectangle.getName() + "面积是:" + rectangle.area());
}
}