This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
    Bookmark Topic Watch Topic
  • New Topic

Object Casting - Wyh is "i = 0"

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hello,
please check out the code as follows.
Why is i=0?
Thomas
class Top
{
public Top() {setvalue();}
int i;
// private void setvalue()
protected void setvalue()
{
i = 2;
System.out.println("Top i =" + i);
}
protected int getvalue() {return i;}
}
class Bottom extends Top
{
int j;
public Bottom() {setvalue();}
// private void setvalue()
protected void setvalue()
{
j = 3;
System.out.println("Bottom j =" + j);
}
// protected int getvalue() {return j;}
}
public class RunIt1a
{
public static void main(String[] args)
{
Top b = new Bottom();
Top T = new Top();
System.out.println( "i = " + T.getvalue() );
System.out.println( "i = " + b.getvalue() );
}
}

C:\jdk1.3\bin>java RunIt1a
Bottom j =3
Bottom j =3
Top i =2
i = 2
i = 0
WHY Is I = 0 and not 2?
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
When new Bottom is called the constuctor of Bottom is called which calls Top's default constructor. In the default constructor u have called setValue(). The setvalue method invoked in the Top's constructor will be that of subclass(u have overriden setValue in Bottom class) since u are creating a instance od Bottom and not of Top.so j =3 and i is still 0 . In the print statement u are calling getValue.Since there is only one getValue method in superclass that method is called and the correct value 0 is printed.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Report post to moderator
Further followups here please. Thanks.
 
    Bookmark Topic Watch Topic
  • New Topic