Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 740
James R. Schmidt Avatar asked Oct 10 '16 12:10

James R. Schmidt


2 Answers

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.

like image 65
Yuriy Yunikov Avatar answered Sep 28 '22 07:09

Yuriy Yunikov


Well The only way i can think around this is if your problem with the size of the object your instance variable stores either you can initialize the parameter to null or you can serialize the object with specifiying your instance parameters to be transient and go with serialize it , deserialize it .

This was just a thought around that , cant think of anything closer.

if you specifically dont need exact inheritance you go around that with creating a custom factory and extract the member variable using reflection , that would work too.

Anyway thats my opinion.

like image 24
Amer Qarabsa Avatar answered Sep 28 '22 08:09

Amer Qarabsa