简体   繁体   中英

Java Generics: Implement multiple sub-interfaces of an generic interface

I've following codes.


interface Observer<T> {
    void update();
}


interface FirstClassObserver extends Observer<FirstClass>{ }


interface SecondClassObserver extends Observer<SecondSecond> { }

Now, I'm required to do as follows.


class MainClass implements FirstClassObserver, SecondClassObserver {
}

But Eclipse give following problem with the code.

The interface Observer cannot be implemented more than once with different arguments: FirstClassObserver<FirstClass> and SecondClassObserver<SecondClass>

Is there a way that I can write my MainClass like


class MainClass implements FirstClassObserver, SecondClassObserver {
   @Override
   void FirstClassObserver::update() { /* ... / } @Override void SecondClassObserver::update() { / ... */ }
}

According to @Ted 's comment. Because of type erasure , you aren't going to be able to do this. Basically, all generic type parameters end up as Object in the compiled byte code.

Also according to @assylias 's comment, there can be ambiguous situation as whose instance of update() method to call MainClass.update() is invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM