简体   繁体   English

在Main类Java中使用具有继承的类

[英]Using classes with inheritance in Main class Java

My super class called Polygon: 我的超级名为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;
}
}

My Square class that extends Polgyon: 扩展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;
}
}

I have a circle and rectangle class pretty much the same thing except with length and width, and circumference. 我有一个圆和矩形类几乎相同的东西,除了长度和宽度,和周长。

In the main class, I want to allow the user to put in an area and then receive the perimeter of a square with that area, circumference of a circle with that area, etc. I don't know if I did it correctly though...I created each object and put in the same input. 在主要类中,我想让用户放入一个区域,然后接收一个方格的周长,该区域,该区域的圆周等。我不知道我是否正确地做了。 ..我创建了每个对象并输入相同的输入。 Here is my main 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() + ".");
}
}

As you can see in my main class, I put in the user input (args[0]) into each constructor's parameter.....which kind of makes the inheritance part of constructors ie super(area)....useless. 正如你在我的主类中看到的那样,我将用户输入(args [0])放入每个构造函数的参数中......哪种构造函数的继承部分即超级(区域)....无用。 Is it necessary to have to create every new shape? 是否有必要创造每一个新的形状? Also, what if I was to implement the Scanner class into the main class? 另外,如果我要将Scanner类实现到主类中呢? Let's say, the user can type in area values and command back information on subclass shapes and then do this with multiple values of area? 假设用户可以键入区域值并命令返回子类形状的信息,然后使用多个区域值来执行此操作? How would I go about doing that, as I have no idea how with having to create objects in the main class. 我将如何去做,因为我不知道如何在主类中创建对象。 We just started using the Main method; 我们刚开始使用Main方法; our IDE for the class is BlueJ, which doesn't require it. 我们这个类的IDE是BlueJ,它不需要它。 I hope my question isn't too confusing with it's wording and I apologize if I formatted this post wrong, as this is my first post. 我希望我的问题不会与它的措辞太混淆,如果我将这个帖子格式错误,我会道歉,因为这是我的第一篇文章。 Thank you. 谢谢。

PS: I forgot to mention to ignore that square is a rectangle. PS:我忘了提到要忽略那个正方形是一个矩形。 My professor made a mistake and by accidentally instructed us to extend rectangle from square. 我的教授犯了一个错误,不小心指示我们从正方形延伸矩形。

PS: besides in the main class, where you guys suggested adding each different shape to a collection and then iterating over each and printing out attributes, do you guys have any other alternatives? PS:除了在主类中,你们建议将每个不同的形状添加到一个集合中,然后迭代每个并打印出属性,你们还有其他选择吗? How would I do it with the Scanner class? 我如何使用Scanner类进行操作? Because in the above situation, I have tl create all the objects. 因为在上面的情况下,我已经创建了所有对象。 I'm trying to get as much practice as possible with main class because I'm severely lacking in it due to BlueJ. 我正试图尽可能多地练习主要课程,因为BlueJ导致我严重缺乏练习。

As far as I can see, it would be best to make Polygon abstract, and have it define an abstract method getPerimiter() : 据我所知,最好将Polygon抽象化,并让它定义一个抽象方法getPerimiter()

public abstract double getPerimiter();

That way, all your subclasses would need their own implementation of that method. 这样,所有子类都需要自己的方法实现。 That's reasonable because they all use different calculations. 这是合理的,因为他们都使用不同的计算。

So you class Polygon would look like this: 所以你的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();
}

And your square, for example, would look like this: 例如,你的广场看起来像这样:

public class Square extends Polygon {

  public Square(double area) {
    super(area);
  }

  public double getPerimiter() {
    return Math.sqrt(area) * 4;
  }

}

All your subclasses must call the constructor defined in Polygon because there's no default constructor, hence the super(area) call in Square. 所有子类都必须调用Polygon中定义的构造函数,因为没有默认构造函数,因此Square中的超级(区域)调用。 Alternatively, you could do away with all the constructors and instead have a setArea(double area) method in Polygon. 或者,您可以取消所有构造函数,而在Polygon中使用setArea(双区域)方法。

Calling super(area) in the constructor is necessary because Polygon doesn't have a constructor with no-args. 在构造函数中调用super(area)是必要的,因为Polygon没有没有args的构造函数。 Yes it is necessary to create every new shape because you work with objects and you need to create them before you can use them. 是的,有必要创建每个新形状,因为您使用对象,并且需要先创建它们才能使用它们。 If you want to practice inheritance with this example you probably want to do something like this in your main: 如果你想用这个例子练习继承,你可能想在你的main中做这样的事情:

 Polygon[] shapes=new Polygon[4];
 shapes[0]=new Polygon(input);
 shapes[1] = new Square(input);
 shapes[2] = new Circle(input);
 shapes[3] = new Rectangle(input);

 for(Polygon p:shapes){
     System.out.println(p.getArea());
 }

And see that all the different objects in the array inherit the getArea() method from Polygon. 并且看到数组中的所有不同对象都从Polygon继承了getArea()方法。 On the other hand if you want to call a specific method that's been provided in the subclass - say getPerimeter() - you have to cast the reference to subclass or you will not be able to use it: 另一方面,如果你想调用子类中提供的特定方法 - 比如getPerimeter() - 你必须将引用转换为子类,否则你将无法使用它:

Polygon mySquare=new Square(100);
System.out.println(((Square)mySquare).getPerimeter());

what you might want, is using a method shared by all your inheritance classes. 您可能想要的是使用所有继承类共享的方法。

Polygon could have a method, which gives you the area - public double calculateArea() but, you don't know, how the classes will calculate their area, so make it abstract Polygon可以有一个方法,它给你区域 - public double calculateArea()但你不知道,类将如何计算它们的区域,所以让它抽象

public abstract double calculateArea()

in Square: 在广场:

public class Square extends Polygon
    {
    private double side;

    public Square(double side)
    {
        this.side= side;
    }

    @Override
    public double calcArea()
    {
        return side * side;
    }


    public double getSide()
    {
        return side;
    }
}

you can now do the same with circle: 你现在可以用圆圈做同样的事情:

public class Circle extends Polygon
    {
    private double radius;

    public Square(double radius)
    {
        this.radius= radius;
    }

    @Override
    public double calcArea()
    {
        return radius * radius * Math.PI;
    }


    public double getRadius()
    {
        return radius;
    }
}

in your Main Method, you set the Radius and the side length of circle and square: 在主方法中,您可以设置圆弧和方形的半径和边长:

Circle c = new Circle(5);
Square s = new Square(5);

and then you can make a List of Polygons, iterate over it, and get the area: 然后你可以创建一个多边形列表,迭代它,并获得该区域:

ArrayList<Polygon> list = new ArrayList<>();
list.add(c);
list.add(s);

for (Polygon element: list){
   System.out.println(list.calcArea());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM