Is it possible to exclude a class instance variable from a subclass in Java?

Perhaps a dumb question, but pretend that the Node class has an instance variable called force. And pretend that the Episode class, which extends Node, does not need strength (other subclasses do). Pretend also that there are many Episode nodes that hold an instance of power. Is there a way in Java to say "this subclass has no variable strength"? I kind of understand why this is probably not allowed, but I thought I would check.

Update: Thank you all. As I expected, the answer to this question is β€œno,” but it creates a Node subclass with variables / methods that the Episode does not need, and then connects other (sub) subclasses that need these variables / methods for this new subclass. , what I want.

+6
source share
2 answers

No, It is Immpossible. You can have, for example, Node and StrengthNode , one without strength and one with it, then the Episode class will expand Node , others will expand StrengthNode .

Also, consider access control in Java, as if the strength was a private variable in Node , it would not be available in the Episode class (only using the getter method), but the instance would exist in memory anyway.

+9
source

Well, the only way I can think about this is that if your problem with the size of the object in your instance variable keeps either you can initialize the parameter to zero, or you can serialize the object by specifying the parameters of your instance to be temporary and go with serialization, deserialize it.

It was just a thought that could not come up with anything closer.

if you don't need exact inheritance, you go around this with creating a custom factory and extract the member variable using reflection, which will work too.

In any case, this is my opinion.

+1
source

All Articles