有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何返回不确定类型?

我有一个名为“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();

它将返回一个Shape类,而不是Square类

但我不想使用:(Square)新Square。更大的()

我希望它能用这种方法自动识别什么是a类

并返回正确的类型


共 (4) 个答案

  1. # 1 楼答案

    我不确定什么是“不确定”类型,但在java中,我们有一个泛型类型,即java可以返回任何类,不管它们是什么

    比如说

    public interface dbDao<T>{
    
        public T t; //this is generic class, all class can use this method  
    
    } 
    

    我希望你能理解我想说的话

  2. # 2 楼答案

    这里不返回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;
        }
    }
    
  3. # 3 楼答案

    您可以重写返回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;
        }
    }
    
  4. # 4 楼答案

    在Java中,重写方法时,实际上可以比接口要求的更具体。例如,接口要求biger返回一个形状,但是从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>{
    }