Forums Register Login

Can We Access Child class members in super class in java ?

+Pie Number of slices to send: Send
Dear Javaranch,
In java can we access child class members in super class?
if yes give me some examples.


Regards
Kademane Gururaja
+Pie Number of slices to send: Send
 

kademane guru wrote:Dear Javaranch,
In java can we access child class members in super class?
if yes give me some examples.



No we can't access any members of child class in parent class;
+Pie Number of slices to send: Send
You can, but it is not what you want. When your program is designed well, superclasses should not know anything about the internals of their subclasses.

Here is an ugly example, in which I cast this to the subclass type (I recommend that you never do this in a real application, this is just to show that it's possible!):

Sometimes, however, you might want to create an abstract superclass that leaves some parts to be implemented by subclasses. This version is much better than the example above, because the superclass doesn't need to cast this to a specific subclass type and doesn't need to access the internals of the subclass:

All of the following truths are shameless lies. But what about this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 16290 times.
Similar Threads
Error in K&B book
Accessibility of private methods in inner classes
protected
Accessing static method with super
is it create object of Base class?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 05:26:43.