我的 super 类名为 Polygon:
public class Polygon
{
private double area;
/**
* Constructor for objects of class Rectangle
*/
public Polygon(double area)
{
this.area = area;
}
/**
* Mutator method that sets the area
*/
public void setArea(double area)
{
this.area = area;
}
/**
* Accessor method that returns the area
*/
public double getArea()
{
return area;
}
}
扩展 Polgyon 的 My Square 类:
public class Square extends Polygon
{
private double perimeter;
/**
* Constructor for objects of class Square
*/
public Square(double area)
{
super(area);
}
/**
* calculates the perimeter of the square using area inherited from Polygon
*/
public void calcPerimeter()
{
perimeter = Math.sqrt(getArea()) * 4; //in a square, area is the square root
}
/**
* Accessor method that returns the perimeter
*/
public double getPerimeter()
{
calcPerimeter();
return perimeter;
}
}
我有一个圆形和矩形类,除了长度、宽度和周长之外,几乎相同。
在主类中,我想允许用户输入一个区域,然后接收该区域的正方形周长、该区域的圆的周长等。我不知道我是否做到了但正确的是......我创建了每个对象并放入相同的输入。 这是我的主要类(class):
public class PolygonMain
{
public static void main(String[] args)
{
double input = Double.parseDouble(args[0]);
Polygon polygon = new Polygon(input);
Square square = new Square(input);
Circle circle = new Circle(input);
Rectangle rectangle = new Rectangle(input);
System.out.println("Area:" + " " + polygon.getArea() + ".");
System.out.println("Perimeter:" + " " + square.getPerimeter() + ".");
System.out.println("Circumference:" + " " + circle.getCircumference() + ".");
System.out.println("Length:" + " " + rectangle.getLength() + ".");
System.out.println("Width:" + " " + rectangle.getWidth() + ".");
}
}
正如您在我的主类中看到的,我将用户输入(args[0])放入每个构造函数的参数中......这使得构造函数的继承部分即 super(area)... 。无用。有必要创造每一个新的形状吗?另外,如果我要将 Scanner 类实现到主类中怎么办?比方说,用户可以输入面积值并命令返回有关子类形状的信息,然后使用多个面积值执行此操作?我将如何去做,因为我不知道如何在主类中创建对象。我们刚刚开始使用 Main 方法;我们的类 IDE 是 BlueJ,它不需要它。我希望我的问题不会与它的措辞太困惑,如果我的这篇文章格式错误,我深表歉意,因为这是我的第一篇文章。谢谢。
PS:我忘了提及忽略正方形是矩形。我的教授犯了一个错误,无意中指示我们从正方形延伸出矩形。
PS:除了在主类中,你们建议将每个不同的形状添加到集合中,然后迭代每个形状并打印出属性之外,你们还有其他选择吗?我将如何使用 Scanner 类来做到这一点?因为在上述情况下,我已经创建了所有对象。我试图在主课上获得尽可能多的练习,因为由于 BlueJ,我严重缺乏主课练习。
最佳答案
据我所知,最好将 Polygon 抽象化,并让它定义一个抽象方法 getPerimiter()
:
public abstract double getPerimiter();
这样,您的所有子类都需要自己实现该方法。这是合理的,因为它们都使用不同的计算。
所以你的 Polygon 类看起来像这样:
public abstract class Polygon {
protected double area; //not private, we want sub-classes to see this field
public Polygon(double area) {
this.area = area;
}
public abstract double getPerimiter();
}
例如,你的正方形看起来像这样:
public class Square extends Polygon {
public Square(double area) {
super(area);
}
public double getPerimiter() {
return Math.sqrt(area) * 4;
}
}
所有子类都必须调用 Polygon 中定义的构造函数,因为没有默认构造函数,因此 Square 中需要调用 super(area)。或者,您可以取消所有构造函数,而在 Polygon 中使用 setArea(double area) 方法。
关于java - 在 Java 主类中使用带有继承的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20243793/