如何在数组中同时调用抽象方法和接口方法?

问题描述 投票:0回答:2

我创建了一个数组来容纳不同的形状。 Circle和Square是从Class Shape扩展的抽象类。 Cube和Sphere来自名为ThreeDShape的界面。我需要找到所有形状的面积以及3D形状的面积和体积,并使用数组对其进行调用。我得到了Test类,可以使用抽象方法。如何获得测试类以使用接口方法?如何在单个数组中打印抽象方法和接口方法?

我还需要使用getClass()方法从数组中调用每个类的详细信息。

public class Test {

public static void main(String[] args) {


        Shape [] shape = new Shape[4];

        Circle circle = new Circle();
        shape[0] = circle;

        ThreeDShape sphere = new Sphere();
        shape[1] = sphere;

        ThreeDShape cube = new Cube();
        cube.volume();
        shape[2] = (Shape) cube;

        Square square = new Square();
        shape[3] = square;



        int x = 3;
        int z = 1;


        for(Shape shape1 : shape) {
            System.out.println("The area of the circle is " + shape1.area());
            System.out.println("The volume of the circle is " + shape1.volume());
            x++;
            z++;
            System.out.println("Found in " + shape1.getClass());
            System.out.println(" ");

        }

    }
public interface ThreeDShape {

    public abstract double volume();

}
public class Cube implements ThreeDShape{

    double a = 5;


    public double volume() {
        return a*a*a;
    }

    public double area() {
        return 6*a*a;
    }


}

public class Square extends Shape {

    double s = 5;

    public double area() {
        return s*s;

    }   
    }

public class Circle extends Shape {

    double r = 9;

    public double area() {
        return r*r*3.14;

    }

}
public class Sphere implements ThreeDShape {

    double r1 = 5;

    public double volume() {
        return ( 4.0 / 3.0 ) * Math.PI * Math.pow( r1, 3 );
    }


    public double area() {
        return 4*3.14*r1*r1;
    }



}
java arrays interface abstract-class abstract
2个回答
0
投票

我更喜欢避免instanceOf,getClass等

public interface OperationalShape {

    double getVolume();

    String getName();



}

0
投票

如果要执行此操作,则需要检查每个形状的类型并在遍历数组时进行投射。类似于:

for(Shape shape1: shape) {
    System.out.println("Area: " + shape1.area());
    if(shape1 instanceof ThreeDShape) {
        System.out.println("Volume: " + ((ThreeDShape) shape1).volume());
    }
}

通常应避免这种类型的检查和类型转换-可能表明程序设计不良。接口和抽象类设计用于具有支持同一API的多种类型的情况。不过,在这里,您有2个不同的API:ShapeThreeDShape

© www.soinside.com 2019 - 2024. All rights reserved.