我有一个名为“Shape”的父类,并在其中编写了一个方法 我希望从它扩展的任何类都可以调用更大的方法用于其他用途。 像这样的简单逻辑:
public abstract Class Shape{
public int size;
public Shape() {}
public Class<? extends Shape> bigger() {
this.size += 1;
return this; // ← Here,How can I return it with unsure type?
}
}
但是我怎样才能在这里返回一个不确定的类型呢? 感谢您的任何想法!
====
如果我有一个 Square extends Shape 类;
我想像这样使用它:
Square S = new Square().bigger();
并且它将返回一个 Shape 类,而不是一个 Square 类。
但我不想使用:(Square) new Square.bigger();
希望用这个方法能自动识别是什么类a
并返回正确的类型。
最佳答案
您可以覆盖返回 Square
(不是 Shape
)的 bigger()
方法。
这是富豪。
public abstract class Shape {
public int size;
public Shape() {}
public Shape bigger() {
this.size += 1;
return this; // ← Here,How can I return it with unsure type?
}
}
public class Square extends Shape {
@Override
public Square bigger() { // returns Square, not Shape
return this;
}
}
关于java - 如何返回不确定的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425130/