File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

Object Casting - Wyh is "i = 0"

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
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

Joined: Feb 27, 2002
Posts: 8898

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.


Groovy
Jim Yingst
Wanderer
Sheriff

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


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Object Casting - Wyh is "i = 0"
 
Similar Threads
Pass By Object
object-oriented programming
Problem loading updated input while expanding in Treeviewer
Object Casting - Wyh is "i = 0"
Editor with JDialog