File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Program Execution Flow." Watch "Program Execution Flow." New topic
Author

Program Execution Flow.

vijay Krishnan
Greenhorn

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();
S.display();
System.out.println("The Value="+S.i);
}
}

*******************************
The above program will gives the output as,

Hai Javaranch
5

**********************************]

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,
Vijay
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: http://aspose.com/file-tools
 
subject: Program Execution Flow.