• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Tim Cooke
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
Saloon Keepers:
  • Piet Souris
Bartenders:

Program Execution Flow.

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic