我有一个名为"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 S = new Square().bigger();
它将返回一个形状类,而不是一个方形类。
但我不想使用:(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;
}
}
您在这里不返回Class
,只需返回一个Shape
。像这样,
public abstract class Shape { // <- class
public int size;
public Shape() {
}
public Shape bigger() { // <-- a Shape. By definition of a sub-class because
this.size += 1; // <-- "this" class is abstract
return this;
}
}
我不确定什么是"不确定"类型,但在 Java 中我们有泛型类型,即 Java 可以返回任何类,无论它们是什么。
例如
public interface dbDao<T>{
public T t; //this is generic class, all class can use this method
}
我希望你明白我想说什么。
在Java中,当你覆盖一个方法时,你实际上可以比接口所要求的更具体。例如,接口需要更大的返回形状,但从形状扩展的 Square 类可以返回 Square,因为 Square 是 Shape。这意味着,如果将其分配给 Square 变量,则在调用 biger 时无需强制转换。
public abstract class Shape { // class not Class
public int size;
public Shape bigger() {
this.size += 1;
return this;
}
}
public class Square extends Shape {
@Override
public Square bigger() {
this.size += 1;
return this;
}
}
这是一种方法,在这种情况下有点令人沮丧,因为它重复了代码。另一种在 C# 中也有效的方法是使用泛型,并限制泛型类型自身实现。这称为奇怪的重复模板模式 https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
public abstract class Shape <S extends Shape>{
public int size;
public S bigger() {
this.size += 1;
return this;
}
}
public class Square extends Shape<Square>{
}