gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:53:56 28 4
gpt4 key购买 nike

下面我有一个调用两个方法的驱动程序。第一个方法的参数类型是扩展 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com