Reputation: 13
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;
}
Upvotes: 1
Views: 3868
Reputation: 8540
you can not override variables in Java.You can have variable with different name.
Upvotes: 0
Reputation: 15229
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;
}
Upvotes: 3
Reputation: 62603
You cannot override fields in Java. When you do what you have just shown us (which compiles fine), you'll only create a different version of the field vertices
in the subclass.
So, if you do Graph graph = new EntityGraph();
, graph.vertices
will hold the value of the one in EntityGraph
.
Upvotes: 0
Reputation: 7116
Concept of overriding is only for non static member functions. Since different variablt type is required for Entity Graph
, either you can declare member variable for Entity Graph
or you can use getters and setters.
Setter in Entity Graph that will set the variable in super class by changing type.
Getter in Entity class that will get variable value from super class, type cast it and will return the value.
Upvotes: 0