The fact that the reference type is of base and the actual object is a sub object, the sub object can use any member (if access modifer allows it) which the base class offers it. Remember that the sub object is STILL A SUB object. So when you try to print out a "sub" field, it will.
Basically, you have a "sub" object, that you are using as a "base" object. It is printing 2 because you have a "sub" object. Accessing the sub variable, is a compile time error because you are trying to use it as a "base" object.
To clarify more on above replies, here is the rule of thumb :
1. Object type determine which overridden method is invoked. This is decided at runtime time.
I'm adding following rule also eventhough its not relavant here.
2. Reference type (not the object type) determine which overloaded method is invoked. This is decided at compile time.
In your case B1.print() invokes the overridden method. Hence prints 2.Hope this helps.
Regards Nalika [ May 31, 2005: Message edited by: Nalika Amarasinghe ]
Joined: May 25, 2005
Regarding your point 2), can you clarify me a bit what you mean by determining which overloaded method? Overloaded methods behave as seperate methods and do not have any relavence to super class methods, do they??
Also can you kindly explain the theoretical explanation between the difference of "referrence type" and "object type"? What is actually the difference between below statements:
base_class base_ref_base_object_class = new base_class(); base_class base_ref_sub_object_class = new sub_class();
Think of the reference type as a remote control (this is explained better in some of the tutorials on the Ranch). I can have a remote control to a basic XYZ brand tv. it has a power button, volume up and down, and channel up and down buttons. it will work with ANY XYZ brand TV.
but then my piture tube blows, so i get a second hand, fancier XYZ tv, with built in surround sound functionality. I can still use my basic remote. when i push the 'power' button, the fancy XYZ tv will turn itself on. The remote just says "hey - turn on" and the TV uses it's own logic to figure out how to do that.
but i can't use my basic remote to control the surround sound features - they're simply not on my remote, so i can't press those buttons. the TV could DO all that stuff, i just don't have any way to TELL it to do them - unless i get a new remote that's the right kind.
in your last example, i have two base references. using those references, i can only call the funtions known to the base class. but when you call a method with the base_ref_sub_object_class reference, since the ACTUAL OBJECT is a sub_class, you'll get the method defined in the sub_class.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: May 25, 2005
Hi Fred.. Great explanation.. Thanks a lot.. Really helped me..