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