【问题标题】:Extended Queesion on "how to refer subclass variable without declaring that variable in parent class?"关于“如何在不在父类中声明该变量的情况下引用子类变量?”的扩展问题?
【发布时间】:2017-10-05 04:11:53
【问题描述】:
public class Test {
    public static void main(final String[] args) {
    B b = new B();
    System.out.println(b);
    }
}

interface MyInterface<T> {
    int getX();
}

abstract class A implements MyInterface {
    @Override
    public String toString() {
    return String.valueOf(getX());
    }
}

class B extends A, implements MyInterface<C> {
    private static final int X = 10;

    @Override
    public int getX() {
    return X;
    }
}

class C  {
    // This is concrete class some 
}

我无法使用泛型来增强此界面。 它在抽象类或实现类中抛出错误。 我怎样才能使它成为可能?

【问题讨论】:

  • 上面的代码还能编译吗?真的不清楚是什么问题?
  • 如果你永远不会使用它,为什么你的接口有一个类型参数T?重点是什么?我无法说出你想要完成什么。 “用泛型增强这个界面”什么也没告诉我。
  • 我将使用那个 T。我没有展示这些细节来简化我的问题
  • 我收到错误消息。接口 MyInterface 不能使用不同的参数多次实现:MyInterface 和 MyInterface。想法是我需要在 A 中使用/调用 getX() 的实现。这就是为什么我需要在 A 中实现 MyInterface
  • 这并没有简化问题,它让人无法回答。你的问题是,“我怎样才能使它成为可能?”——我不知道你试图使什么成为可能,因为你已经简化了所有重要信息。

标签: java oop inheritance polymorphism abstract


【解决方案1】:

你的意思是这样的吗?

public class Test {
    public static void main(final String[] args) {
        MyInterface b = new B();
        System.out.println(b);
    }
}

interface MyInterface<T> {
    T getX();
}

abstract class A<T> implements MyInterface {
    @Override
    public String toString() {
        return String.valueOf(getX());
    }
}

class B extends A {
    //private static final int X = 10;
    private static final double X = 10;

    //@Override
    public Double getX() {
        return X;
    }
}

【讨论】:

    【解决方案2】:
    public class MyTest2 {
        public static void main(final String[] args) {
        B b = new B();
        System.out.println(b);
        }
    }
    
    interface MyInterface<T> {
        int getX();
    }
    
    abstract class A<T> implements MyInterface {
        @Override
        public String toString() {
        return String.valueOf(getX());
        }
    }
    
    class B extends A<C>  {
        private static final int X = 10;
    
        @Override
        public int getX() {
        return X;
        }
    }
    
    class C  {
        // This is concrete class some
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 2012-05-05
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 2019-10-15
      相关资源
      最近更新 更多