Introduction
Instance variables are an important part of object-oriented programming, as they allow us to store data associated with an object. When a superconstructor is used, the instance variables created within it can be accessed and changed by the subclass. In this article, we will discuss how to access and change the instance variables created within a superconstructor. We will look at the different ways to access and change the instance variables, as well as the advantages and disadvantages of each approach. By the end of this article, you will have a better understanding of how to access and change the instance variables created within a superconstructor.
Solution
You can access and change the instance variables created within a superconstructor by using the “this” keyword. For example, if you have a superconstructor with an instance variable called “name”, you can access and change it by using the following code:
this.name = “newName”;
JLabel
is a subclass of JContainer
. JContainer
offers a public method named setFont(), so you can call it from any place in your program, where you have a reference to the label object (the Lives’ constructor is a valid place though).
The possbility to change a super class’ attribute depends on its visibilty (for example protected) and available accessor methods (for example getName()
and setName()
).
If an attribute/accessor was declared public or protected, you can change it directly from inside the subclass. In case of default visibilty, the subclass needs to be in the same package as the super class to manipulate the respective attribute.
solved How to access and change the instance variables created within a superconstructor?