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

Upcasting

Amit KumarS
Ranch Hand

Joined: Oct 10, 2003
Posts: 100
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


****************************<br />In 24 hrs Earth rotates once on its Axis.
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8898

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.


Groovy
deep venu
Ranch Hand

Joined: Jun 09, 2001
Posts: 56
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

Joined: Aug 20, 2001
Posts: 1815
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.


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Amit KumarS
Ranch Hand

Joined: Oct 10, 2003
Posts: 100
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Upcasting
 
Similar Threads
Overriding
Super and subclass
Inheritance
Static methods & Overriding!
Polymorphism