Search code examples
javatemplatesinheritancetypesextend

Overriding a variable when extending a class with a different type in Java


I want to extend a class as shown in the below example. While extending, I just want to change the type of one variable; declaring the same variable name with a different type will do this?

class Graph {
    LinkedList<Node> vertices;
}


class EntityGraph extends Graph {
    LinkedList<Entity> vertices; 
} 

Solution

  • First off, making you variable acces type "protected" rather then default would be better in this scenario (i.e, make it protected in Graph class, and protected or less restrictive in EntityGraphClass).

    Then you can type your Graph class such as :

    class Graph<T> {
    
    protected LinkedList<T> vertices;
    
    }
    

    then do a

    class EntityGraph extends Graph<Entity> {
         //no longer needed
        //LinkedList<Entity> vertices; 
    } 
    

    and you'll get an implementation of the Graph class (in the EntityGraph class) that has a List of Entity types;

    If Entity extends Node, and you want the elements in the list to be of at least Node type, you can do:

    class Graph<T extends Node> {
    
        protected LinkedList<T> vertices;
    
    }