Iが与えられた問題:境界と領域を取得する抽象クラスを作成しますか?
形状をカプセル化する抽象スーパークラスを書く形状の周囲を返す一靴の領域を返す別の:形状は、2つの抽象メソッドを有します。また、定数フィールドPIがあります。このクラスには、抽象クラス以外の2つのサブクラスがあります.1つは円をカプセル化し、もう1つは長方形をカプセル化します。円は1つの追加の属性、その半径を持っています。長方形には、幅と高さという2つの属性が追加されています。また、これら2つのクラスをテストするためにクライアントクラスを含める必要があります。
ここで私がやった仕事だ:
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の定数フィールドはCircleクラスではなくShapeクラスにある必要がありますか?もしそうなら、サークルクラスから取り除く方法と、シェイプクラスに配置する方法を教えてください。
必要に応じて、抽象クラスでpublic static final int PI = 3.17にすることができます。 Parentクラスのすべての定数を宣言する必要があります。しかし、ちょうど学校のプロジェクトとあなたは決してPI値を使用する形状の詳細を宣言するつもりはありません。 –