java - 我应该选择哪种参数类型?扩展父类(super class)型或父类(super class)型的泛型

标签 java generics methods

下面我有一个调用两个方法的驱动程序。第一个方法的参数类型是扩展 Polygon 的泛型类型。第二种方法的参数类型是Polygon。两者都要求我强制转换参数才能调用子类方法。哪个更好?为什么我应该使用其中一种而不是另一种?

public class Driver {
        public static void main(String[] args) {

                Square s1;
                try {
                        s1 = new Square(new Point(0,0), new Point(0,1), new Point(1,1), new Point(1,0));
                }
                catch (IllFormedPolygonException e) {
                        System.out.println(e.toString());
                        return;
                }

                System.out.println(s1.toString());
                printArea(s1);
                printArea2(s1);
        }

        public static <T extends Polygon> void printArea(T poly) {
                System.out.println(poly.getArea());

                if (poly instanceof Triangle) {
                        ((Triangle)poly).doTriangleThing();
                }
                else if (poly instanceof Square) {
                        ((Square)poly).doSquareThing();
                }
                else {
                        System.out.println("Is polygon");
                }
        }

        public static void printArea2(Polygon poly) {
                System.out.println(poly.getArea());

                if (poly instanceof Triangle) {
                        ((Triangle)poly).doTriangleThing();
                }
                else if (poly instanceof Square) {
                        ((Square)poly).doSquareThing();
                }
                else {
                        System.out.println("Is polygon");
                }
        }
}

最佳答案

选择 super 类型。来自 generics tutorial :

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used.

如果参数/返回类型之间没有关系,那么泛型不会添加任何内容;它只会使代码更难阅读,因此应该首选更简单的解决方案。

这是一个通用方法很有用的示例。假设您有一个方法,它接受一个 Polygon 并返回一个一半大小的副本。因为返回类型与参数类型相同,所以可以使用泛型来避免客户端代码中的强制转换:

public static void main(String[] args) {
    Square square = new Square(0, 0, 10, 10);

    // Without the generic it's necessary to cast the return value
    square = (Square) shrink(square);

    // Cast not needed with generic
    square = shrinkWithGenerics(square);
}

public static Polygon shrink(Polygon poly) {
    // ...
}

public static <T extends Polygon> T shrinkWithGenerics(T poly) {
    // ...
}

关于java - 我应该选择哪种参数类型?扩展父类(super class)型或父类(super class)型的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047260/

相关文章:

java - 交换数组中的第一个和最后一个值(JAVA)

JavaFX:在 SplitPane 中隐藏带有 slider 的固定 Pane

java - apache poi jar 缺少类文件

java - 通过反射调用构造函数而不使用泛型进行强制转换

r - 在 R 的 scales 包中,为什么 trans_new 使用反参数?

java - 生产者消费者模式——处理生产者失败

java - 泛型类型的浅拷贝

c++ - C 中的模板在 C++ 中使用 void *

flutter - Dart Flutter如何在类内部初始化类方法?

javascript - 微调性能时,多次调用 JavaScript 方法的最佳方式是什么?