What is the use instance variable in superclass , and how to change their values in subclasses

StackOverflow https://stackoverflow.com/questions/22844602

  •  27-06-2023
  •  | 
  •  

i am new to java , please explain me , what is the use of instance variable in superclasses as we cant override them in sub classes like methods . How can we change the values of instance variable of superclass in subclasses and please also explain how you had this !!!!!! . And if we had simply changed its value , then while using polymorphism the value in superclass will return , and not what , we had changed it in the subclass

有帮助吗?

解决方案

The importance of instance variables in superclasses is that they will be inherited by all the subclasses of that superclass, reducing code redundancy. To alter the value of set the value of a private instance variable from a superclass use the super keyword in the constructor of the subclass. To alter the value of the instance variable after instantiation use a mutator (setter) method defined in the superclass. By convention the mutator method would be named setVariable().

其他提示

Variables cannot be overriden. If you declare a variable with the same name in subclass, they are just different variables. Those methods in superclass which access the old variable still continue to read and write that variable, and methods in subclass access new variable. To access old variable from subclass, super.variableName construct can be used.

Only protected, public and default (with no modifier) variables can be modified in subclasses. You don't have access to private variables inside subclasses.

To modify a variable all you need to do is change its value like you would in your superclass. However you can't override variables like methods, as Java doesn't support that at all. All you can do is change their values.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top