Say I had a class SuperClass and two subclasses SubClassA and SubClassB that inherit from SuperClass.
abstract class SuperClass{
...
List someList;
...
}
class SubClassA extends SuperClass{
...
List<String> someList;
...
}
class SubClassB extends SuperClass{
...
List<Integer> someList;
...
}
That way it is convenient because I can get someList.size() in Superclass and have Typesafety in the Subclasses.
The problem is that it does not “feel” right, can you think of potential hazards this apporach has that I am not aware of?
For one thing, any method of
SuperClasssees the superclass list, not that of the subclass. This almost surely leads to subtle bugs. E.g. when you saywhat you actually get is the size of the list in
Superclass, not that of the subclass. The superclass list may be empty while the subclass list contains elements (or vice versa).The reason behind this is that
SubClassA.someListdoes not in any way replace or overrideSuperclass.someList– it just shadows it, so the subclass methods seeSubClassA.someListinstead ofSuperclass.someList. However, this has absolutely no effect inSuperclass. Methods can be made virtual (and in Java, they are by default), but data members can’t.