-1

Say I have a interface

interface Rankable {}

and two classes implement this interface

class Worker implements Rankable {}
class Student implements Rankable {}

Now I define a generic class

class Node<T extends Rankable> {
    T data;
    Node left;
    Node right;
    Node parent;
};

Actually I don't know why use extend here.
Then I define a class BST

class BST<T extends Rankable> {
    //field
    Node root;
    //method
    void insert(Node node){};
};

So, I convert Student and Worker to Node, Can I have two different Node types (Node<Student> Node<Worker>). in the same BST<T>.
If answer yes, why? How that extends a interface work?

List list = new ArrayList();
list.add(1);
list.add("hello");
//Why this code cannot work, I think it's same with code above

I'm new to Java, Please be patient.

DoubleX
  • 351
  • 3
  • 18
  • 1
    `Node left` should be `Node left`, same for `right`, `parent` and `root`. – luk2302 Apr 18 '18 at 08:39
  • 1
    You're using a raw `Node` in your `BST` class and `Node` class. – Mena Apr 18 '18 at 08:39
  • @luk2302 I try to understand how it works, is there a inheritance definition in this question? I never define a abstract class, so I thought there is no superclass and subclass notation. – DoubleX Apr 18 '18 at 08:41
  • Possible duplicate of [When do Java generics require extends T> instead of and is there any downside of switching?](https://stackoverflow.com/questions/897935/when-do-java-generics-require-extends-t-instead-of-t-and-is-there-any-down) – luk2302 Apr 18 '18 at 08:42
  • and https://docs.oracle.com/javase/tutorial/java/generics/bounded.html – luk2302 Apr 18 '18 at 08:43

1 Answers1

2

Your implementation is not completely generic so this time you can add both types but the are not use generic.

If you add following changes the class is completely generic. Then answer is no you can have one type which you define in T

class Node<T extends Rankable> {
  T data;
  Node<T> left;
  Node<T> right;
  Node<T> parent;
};

class BST<T extends Rankable> {
  //field
  Node<T> root;
  //method
  void insert(Node<T> node){};
};

As a example:

BST<Student> bst = new BST<>()

bst is accept Node Student type only. And left,right and parent of Node also accept student only.

janith1024
  • 1,042
  • 3
  • 12
  • 25
  • BST bstStudent = new BST<>(), BSTbstWorker = new BST<>() then you can have both in different instance – janith1024 Apr 18 '18 at 09:01
  • 1
    `BST` accepts both types. But the nodes will still be `Node` potentially containing `Student` instances. – luk2302 Apr 18 '18 at 09:03
  • @janith1024 no, only if he needs specific methods of those instances, but a `getRank` can be called on all `Rankable`s, that is the entire purpose of the interface. – luk2302 Apr 18 '18 at 09:05