java - 如何返回不确定的类型?

标签 java polymorphism

我有一个名为“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/

相关文章:

java - 父构造函数调用的方法表现为子方法

python属性和继承

java - 取消用户输入

java - 如何在主线程上调用 getLooper()?

java - 考虑以下用 Java 编写的程序。为什么这个输出**2 2**。我认为这应该是输出 **1 1**

c# - 当一种类型需要额外的属性时尝试实现多态性

scala - 如何检查值可见类型

java.sql.SQLException : No suitable driver found jdbc:oracle:thin 异常

java - 如何在 Java-mysql 中验证用户名和密码?

c++ - 使用一个实现其他类方法的类方法以及它自己的类方法