Can I make a superclass's variable static final in subclass?

abstract class User {
String about;
}
class Bots extend User {
final static String about = "Bots are not humans"; // I think this replaces Superclass 's instance variable about
}
abstract class User {
String about;
}
class Bots extend User {
final static String about = "Bots are not humans"; // I think this replaces Superclass 's instance variable about
}
13 Replies
JavaBot
JavaBot4d ago
This post has been reserved for your question.
Hey @sadstephen! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
dan1st
dan1st4d ago
you cannot replace variables of subclasses and especially not make them static or final the only thing you can do is assigning them in the constructor or creating more variables
sadstephen
sadstephenOP4d ago
I just want to understand what is the effect of doing that - we have a definition of instance variable about in superclass; then in subclass we are creating a static variable in the same variable name.
Snake
Snake4d ago
Good question. The effect should be that both separate variables still exist, but the one in the subclass shadows the one in the superclass. So if you write about in the subclass, it will refer to Bots.subclass.
sadstephen
sadstephenOP4d ago
is it called polymorphism?
Snake
Snake4d ago
No.
sadstephen
sadstephenOP4d ago
or encapsulation or something 😦
Snake
Snake4d ago
Polymorphism is when you have an instance of a subclass in a superclass-type variable. Encapsulation is just when one object is a field in another. When these variables use the same name, you get shadowing, but the names being the same doesn’t result in encapsulation or polymorphism.
sadstephen
sadstephenOP4d ago
Thank you for your time. ❤️
JavaBot
JavaBot4d ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
dan1st
dan1st4d ago
it results in you having two variables with the same name as mentioned by Snake, yes if you access the variable from User, you get User#about and from Bots, you get Bots.about
sadstephen
sadstephenOP4d ago
I think about is not static variables in superclass User.
JavaBot
JavaBot4d ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?