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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Object Casting - Wyh is "i = 0"

 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 8945
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Further followups here please. Thanks.
 
What I don't understand is how they changed the earth's orbit to fit the metric calendar. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
    Bookmark Topic Watch Topic
  • New Topic