• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private member access

 
Sudhanshu Mishra
Ranch Hand
Posts: 236
1
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sudhanshu Mishra
Ranch Hand
Posts: 236
1
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic