Search code examples
javainheritancesubclassinstance-variables

Can a class instance variable be excluded from a subclass in Java?


Possibly a dumb question, but pretend class Node has an instance variable called strength. And pretend class Episode, which extends Node, does not need strength (other subclasses do). Pretend also that there are a LOT of Episode nodes all storing an instance of strength. Is there any way in Java to say "this subclass does not have a strength variable"? I'm kind of seeing why this probably isn't allowed, but thought I'd check.

Update: Thanks all. As I suspected, the answer to this question is "no," but creating a subclass of Node with the variables/methods not needed by Episode, then connecting the other (sub)subclasses that need these variables/methods to that new subclass will do exactly what I want.


Solution

  • No, it's not possible. You can have e.g. Node and StrengthNode classes, one without strength and one with it, then Episode class will extend Node, others will extend StrengthNode.

    Also, take into account the access control in Java, as if strength is a private variable in Node, it will not be accessible in Episode class directly (only using getter method), but it's instance will exist in memory anyway.