扩展Queesion“如何在不声明父类中的变量的情况下引用子类变量?”

时间:2017-10-05 04:11:53

标签: java oop inheritance polymorphism abstract

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 
}

我无法使用泛型增强此接口。 它在抽象类或实现类中抛出错误。 我如何使它成为可能?

2 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

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;
    }
}

答案 1 :(得分:0)

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
}