• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Upcasting

 
Amit KumarS
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all...
i am stuck with a small theoritical problem.. when we assign an object of derived class to an object of base class and we call a method then the derived class method is called...
but i came across the following code..

i expected it to give call the Dervied's method.. but it is giving an exception saying..

Derived.java:13: foo() has private access in Base

i am not able to understand WHY?? as the rule the derived class should be called.. so i have nothing to do with the access specifier of the method of Base class...
So, can some one please clear my concept on this..
Thanks in advance for your time and efforts..
Thanks
Amit
 
Pradeep bhatt
Ranch Hand
Posts: 8933
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is beacuse the method foo is private in the Base class.
Even though you have assigned Derived class instance to h, the compiler will be aware of this.
The object h can represent the derived class instance or the base instance. If it is base then the method foo has a private access so will not be accessible, so the error.
 
deep venu
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling a method on an object depends on the data type of the reference which in this case is the base class and since its private...
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to be clear:
Calling a method on an object does not depend on the reference type to the object. Instead, the access permissions depend on the reference type to the object. Since access permissions are checked at compile time, the javac compiler has no way of knowing what the actual type of the object is other than its declared reference type. So the compiler will stop you if you are doing things wrong, like trying to access methods you don't have access to.
And if you think about it, this is exactly what the compiler should do.
 
Amit KumarS
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all..
thanks a lot... i got u alls point.. actually i was thinking about the status at the runtime and not the compile time but the error is at compile time... thus, i got confused
thanks a lot for ur support and time
Regards
Amit
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic