wood burning stoves
The moose likes Beginning Java and the fly likes Superclass and subclass reference type confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Superclass and subclass reference type confusion" Watch "Superclass and subclass reference type confusion" New topic
Author

Superclass and subclass reference type confusion

supriya riya
Ranch Hand

Joined: Feb 23, 2009
Posts: 41
hi,
I have confusion regarding the output which is: sub1 2
But i can't understand why obj.i prints value 1 rather than 2
as the actual type of obj is B at run time ( it calls obj.myInt of class B???). So it must print sub2 2.
Not getting overriding concept right.Confused what gets called subclass /super class method depending on reference type.
Below is the code




Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 20057
    
  44

supriya riya wrote:
I have confusion regarding the output which is: sub1 2
But i can't understand why obj.i prints value 1 rather than 2
as the actual type of obj is B at run time ( it calls obj.myInt of class B???). So it must print sub2 2.
Not getting overriding concept right.Confused what gets called subclass /super class method depending on reference type.


Polymorphism only applies to method calls -- and specifically, only non-static method calls where overriding is taking place. For variables (either static or instance) and for other types of methods calls (such as static methods or private methods), it is completely resolved at compile time.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
supriya riya
Ranch Hand

Joined: Feb 23, 2009
Posts: 41
thanks
 
Have you checked out Aspose?
 
subject: Superclass and subclass reference type confusion
 
It's not a secret anymore!