简体   繁体   English

在对象数组中选择特定对象

[英]choosing specific object in an array of objects

public abstract class ShapeClass {
    private double area;

    CONSTRUCTORS
    MUTATORS, ACCESSORS

    public abstract double calcArea();
}

public class CircleClass extends ShapeClass {
    private int diameter;
    private double area;

    public CircleClass() {
        super();
        diameter = 10;
    }

    public CircleClass(CircleClass inCircle) {
        super(inCircle);
        diameter = inCircle.getDiameter();
    }

    public CircleClass(int inDiameter) {
        setDiameter(inDiameter);
        area = calcArea();
        super.setArea(area);
    }

    public void setDiameter(int inDiameter) {
        if(validateInt(inDiameter)) {
            diameter = inDiameter;
        } else {
            throw new IllegalArgumentException("invalid diameter");
        }
    }

    public int getDiameter() {
        return diameter;
    }

    public boolean equals(int inDiameter) {
        return(diameter == inDiameter);
    }

    public boolean equals(Object inObj) {
        boolean same = false;
        if(inObj instanceof CircleClass) {
            CircleClass inCircle = (CircleClass)inObj;
            if(super.equals(inCircle)) {
                if(diameter == inCircle.getDiameter()) {
                    same = true;
                }
            }
        }

        return same;
    }

    public String toString() {
        return (" area of circle is: " + super.toString());
    }

    private boolean validateInt(int inDiameter) {
        boolean valid = false;
        if (inDiameter>0) {
            valid = true;
        }
        return valid;
    }

    private boolean validateReal(double inArea) {
        boolean valid = false;
        if(inArea>0.0) {
            valid = true;
        }
        return valid;
    }

    @Override
    public double calcArea() {
        double radius;
        radius = ((double) diameter) / 2.0;
        area = Math.PI * radius * radius;
        return area;
    }
}

This is my code for a ShapeClass . 这是我的ShapeClass代码。 I have two other classes Rectangle and Triangle , they're pretty much the same as the CircleClass . 我还有另外两个RectangleTriangle类,它们与CircleClass几乎相同。

In another class i'm assigning the ShapeClass objects in an array. 在另一个类中,我在数组中分配ShapeClass对象。

if I do that it'll be something like shape[3] = {Shape Object,Shape Object,Shape Object}. 如果我这样做,它将是shape [3] = {Shape Object,Shape Object,Shape Object}之类的东西。 I don't know if that's right, I'm new to java. 我不知道这是对的,我是Java新手。 Sorry if there's any confusion. 对不起,有什么困惑。

My question is if I do that how do I distinguish what object is Circle , Rectangle or Triangle ? 我的问题是,如果我要怎么区分CircleRectangleTriangle是什么对象? When I want to print out a circle object only? 当我只想打印圆形对象时?

Thanks for the help. 谢谢您的帮助。

You can check by using instanceof : 您可以使用instanceof检查:

if(shape[0] instanceof Circle){
 // do something
}

So there is an operator in java - instance of: 所以在Java中有一个运算子-的执行个体:

if(shapeObject instanceof Circle){
  //print
}

so you can use it to distinguish objects by type. 因此您可以使用它按类型区分对象。 Also as for your question whether it's correct: You can use this approach with creating array of parent object type and putting children in it. 另外,关于您的问题是否正确:您可以使用这种方法创建父对象类型的数组并将子对象放入其中。 After that, if you call toString method on each object from that array specific implementation of that method will be invoked. 之后,如果您从该数组中的每个对象上调用toString方法,则将调用该方法的特定实现。 For example if there is Circle object in this array and there is overridden toString method in it then after calling toString on object from array of ShapeObject specific implementations will be invoked. 例如,如果此数组中有Circle对象,并且其中重写了toString方法,则在从ShapeObject数组中的对象上调用toString之后,将调用特定的实现。

You have 2 options: 您有2个选择:

// Solution 1: prits out all instances of Circle, basically also all subclasses of Circle
for (ShapeClass shape : shapes) {
    if (shape instanceof CircleClass)
        System.out.println(shape.toString());
}

//  Solution 2: Matches exact class
for (ShapeClass shape : shapes) {
    if (shape.getClass().equals(CircleClass.class))
        System.out.println(shape.toString());
}

The above solutions will solve the task you asked about. 以上解决方案将解决您所要求的任务。 But maybe the information below will be userful for you: 但也许以下信息对您有用:

What if you want to print out the names of each shape, how to distingush them in this case? 如果要打印每种形状的名称,在这种情况下如何区分它们怎么办?

Let's say we have 3 shapes: 假设我们有3种形状:

public class Shape {
   public void print() {
       System.out.println("Shape is printed");
   }
}

public class Triangle extends Shape {
   @Override
   public void print() {
       System.out.println("Triangle is printed");
   }
}

public class Circle extends Shape {
   @Override
   public void print() {
       System.out.println("Circle is printed");
   }
}

This code will print exactly what you need, because you defined the same function for all of the shapes, overriding it in child classes, and the appropriate function will be called based on object type determined at the runtime: 这段代码将完全打印您所需的内容,因为您为所有形状定义了相同的函数,并在子类中将其覆盖,并且将根据运行时确定的对象类型来调用适当的函数:

for (Shape shape : shapes) {
    shape.print();
}

Try like this, 这样尝试

for(int i = 0; i < shapeArray.length; i++){
    if(shapeArray[i] instanceof CircleClass){
          // print circle here
     }
 }

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

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