This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Program Execution Flow. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Program Execution Flow." Watch "Program Execution Flow." New topic

Program Execution Flow.

vijay Krishnan

Joined: Jul 27, 2006
Posts: 14
Hello all,

i had one doubt in this below program, i don't know how it is working in java compliler or how java treats this code line by line.

The Code is:

class Super
int i=5;
void display()
System.out.println("Hello Java:");

class Sub extends Super
int i=7;
void display()
System.out.println("Hai Javaranch:");
class Main
public static void main(String[] args)
Super S = Sub();
System.out.println("The Value="+S.i);

The above program will gives the output as,

Hai Javaranch


My question is, i had created the object for Super class and i had assigned it to Sub class.

while accessing it takes the method of Subclass method.
but, while accessing the variable it takes the Superclass variable.
i don't know why.

please any one explain the below line which is in the program also,

//Super S = new Sub();


Thanks in Advance,
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
Your variable i is by default inherited from super. Since you declare it again, you are shadowing the declarion in the super class. How coud you distinguish the varible i declared in the super class than that declared in the child class?

Well, it is resolved pretty simple. When the variable is shadowed, in order to decide which of the two you want to access, the runtime will give you the value of the variable that corresponds to the type of the object that you are using to access it.

If you cast your object to a Sub type then you will get the value of the i variable declared in the subclass.
I agree. Here's the link:
subject: Program Execution Flow.
It's not a secret anymore!