File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Object Casting - Wyh is Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic

Object Casting - Wyh is "i = 0"

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
please check out the code as follows.
Why is i=0?
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

Joined: Feb 27, 2002
Posts: 8927

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 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

Joined: Jan 30, 2000
Posts: 18671
Further followups here please. Thanks.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Object Casting - Wyh is "i = 0"
jQuery in Action, 3rd edition