File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Private member access Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Private member access" Watch "Private member access" New topic
Author

Private member access

Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 217

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...
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3068
    
  33

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.


Mohamed Sanaulla | My Blog
Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 217

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?
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3068
    
  33

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.
 
Don't get me started about those stupid light bulbs.
 
subject: Private member access