Using method on object in overriden abstract generic function in Java

时间:2018-03-25 18:52:27

标签: java oop generics

Here is the following code

public abstract class A {
    public abstract <E> void foo(E e);
}

the subclass:

public class B extends A {
    @Override
    public <OtherClass> void foo(OtherClass oc) {
        oc.someOtherClassMethod(); //here compiler cannot see method
    }
}

and class with main

public class C {
    public static void main(String[] args) {
        OtherClass oc = new OtherClass();
        A a = new B();
        a.foo(oc);
    }
}

the error I get:

 error: cannot find symbol
...
symbol:   method someOtherClassMethod()
  location: variable oc of type OtherClass
  where OtherClass is a type-variable:
    OtherClass extends Object declared in method <OtherClass>write(OtherClass )
1 error

Why cannot I use the someOtherClassMethod()? Without generics everything works, but I would like to be able to extend other classes in which I override foo() method

Solution:

public abstract class A <E> {
    public abstract void foo(E e);
}

Subclass:

public class B extends A<OtherClass> {
    @Override
    public void foo(OtherClass oc) {
        oc.someOtherClassMethod();
    }
}

However, now I need use in main function:

A<OtherClass> a = new B();

1 个答案:

答案 0 :(得分:1)

尝试

public abstract class A<E> {
  public abstract void foo(E e);
}

public class B extends A<OtherClass>