Forums Register Login

Private member access

+Pie Number of slices to send: Send
Hi all,
I am confused about the method access using only a reference in the case where,a private method of class is not inherited,and then even after polymorphic assignment,invoking the method by superclass reference invokes the superclass's method.Does the JVM not sees the original object in this case?





Please help me get this doubt clear.
Thanks...
+Pie Number of slices to send: Send
Private methods are not inherited by the Sub Class. So there is no polymorphic calls with respect to them. Moreover these methods are accessible only with in the class declaration.
+Pie Number of slices to send: Send
Yes,I do agree,but its just the fact that -"At runtime the JVM looks for the actual object on the other side of reference before invoking the method" that is confusing me.
Does this happen only in case of overriden methods?Dont we need an actual object to invoke a method?But in this case i dont have an object of T,still i am able to invoke method of T by just using T's reference?
WHY?
+Pie Number of slices to send: Send
Its only in case of overridden methods that the JVM checks the actual object and invokes if the overridden version.

Dont we need an actual object to invoke a method?


Yes, but we do know that the Sub class instance can be assigned to the super class reference and the reference type decides which methods can be invoked on the instance.
For example if you had an extra method in the sub class say placement2() which is not present in the Super class, then when you try to invoke

you would get an error because the compiler is not aware of the existence of the method placement2() in the class T.


But in this case i dont have an object of T,still i am able to invoke method of T by just using T's reference?


As you are invoking the placement() from the class T itself, the compiler is able to locate the method against the reference of type T. So its at compile time that these bindings happen.
But when you try to move the main method out from class T into class K, things would be different- You get a compiler error as at compile time the compiler says that the method has private access.
Life just hasn't been the same since the volcano erupted and now the air is full of tiny ads.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 927 times.
Similar Threads
can one access private methods of a superclass with a sub class reference?
overriding private methods
Regular Inner class
Can a private method be overridden by a subclass ?
Inheritance Question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:15:21.