Home > front end >  java generics with inheritance and interfacec
java generics with inheritance and interfacec

Time:09-17

I have already created a class called priority queue.

public class PriorityQueue<T> implements Iterable<T>

And now, I want to create a class SpecialPriorityQueue<T> with these details.

  1. While T in PriorityQueue can be any type, T in SpecialPriorityQueue has to implement an interface.
  2. SpecialPriorityQueue inherits from PriorityQueue, and it override some methods and uses some protected field of the PriorityQueue.

Is there any clean way to do this without changing the code of PriorityQueue?

CodePudding user response:

Not sure if I understand your question correctly, but - yes, sure you can accomplish all of that.

  1. You just declare SpecialPriorityQueue with a restricted type:

      public class SpecialPriorityQueue<T extends AnInterface> extends PriorityQueue<T> 
    
  2. Overriding methods and using protected fields from the parent class is straightforward:

      @Override
      public void inheritedMethod() {
          // just use inherited protected fields here
      }
    

CodePudding user response:

public class SpecialPriorityQueueu<T extends YourInterface> extends PriorityQueue<T>

Then to use protected fields and override methods you do it as you would do for any class

  • Related