我給出的問題:創建一個抽象類來獲取周邊和區域?
編寫一個封裝形狀的抽象超類:一個形狀有兩個抽象方法:一個返回形狀的周邊,另一個返回鞋的區域。它也有一個名爲PI的常量字段。這個類有兩個非抽象的子類:一個封裝一個圓,另一個封裝一個矩形。圓有一個額外的屬性,其半徑。矩形有兩個額外的屬性,其寬度和高度。您還需要包含一個客戶端類來測試這兩個類。
下面是我所做的工作:
Shape.java
public abstract class Shape
{
public abstract double getPerimeter();
public abstract double getArea();
}
Circle.java
public class Circle extends Shape
{
private double radius;
final double pi = Math.PI;
//Defualt Constructor, calls Shape default constructor
public Circle()
{
//Set default value to radius
this.radius = 1;
}
public Circle(double radius)
{
this.radius = radius;
}
public double getArea()
{
//Return πr^2 (area formula)
//Use Math.pow method (page 141) in order to calculate exponent
return (pi * Math.pow(radius, 2));
}
public double getPerimeter()
{
//Return 2πr (perimeter formula)
return (2 * pi * radius);
}}
Rectangle.java
public class Rectangle extends Shape
{
private double width, height;
public Rectangle()
{
//set default value to width and height
this.width = 1;
this.height = 1;
}
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double getArea()
{
return width * height;
}
public double getPerimeter()
{
return 2 * (width + height);
}}
ShapeClient.java
public class ShapeClient {
public static void main(String [] args)
{
// To test Rectangle...
double width = 13, length = 9;
Shape rectangle = new Rectangle(width, length);
System.out.println("The rectangle width is: " + width
+ " and the length is: " + length
+ "The area is: " + rectangle.getArea()
+ "and the perimeter is: " + rectangle.getPerimeter() + ".");
//To test Circle...
double radius = 3;
Shape circle = new Circle(radius);
System.out.println("The radius of the circle is: " + radius
+ "The area is: " + circle.getArea()
+ "and the perimeter is: " + circle.getPerimeter() + ".");
}}
我的問題是:PI的常量字段是否需要在Shape類而不是Circle類中?如果是這樣,我應該如何將它從圈子類中取出,我應該如何將它放置在Shape類中?
如果需要,您可以在Abstract類中使public static final int PI = 3.17。正如你應該在你的父類中聲明所有的常量一樣。但是它的公正學校項目和你永遠不會聲明更多使用PI值的形狀。 –