• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors

 
Sony Thomas
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found the following code at javacamp.org and could not understand the solution
class A
{
public A() {
PrintFields();
}
public void PrintFields() {}
}
class B extends A
{
int x = 1;
int y;
public B() {
y = -1;
}
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
}
class Test
{
public static void main(String[] args) {
B b = new B();
}
}
output:
x = 0 y = 0
I thought that the answer would be x=1 and y=0
Please help. Thanks
 
Phil Rhodes
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When dealing with this kind of code, it helps me to put
println() calls in different places, so I can see what's
happening. Like so:
class A
{
public A()
{
System.out.println( "in A() ctor" );
PrintFields();
}
public void PrintFields()
{
System.out.println( "in A.PrintFields()" );
}
}
class B extends A
{
int x = 1;
int y;
public B()
{
System.out.println( "in B() ctor" );
y = -1;
}
public void PrintFields()
{
System.out.println( "in B.PrintFields" );
System.out.println("x = "+x+" y = "+y);
}
}
class Test
{
public static void main(String[] args)
{
B b = new B();
}
}
Now, when I execute the code, I get:
in A() ctor
in B.PrintFields
x = 0 y = 0
in B() ctor
which tells me that A's constructor executes as expected, but
that the call to PrintFields() that happens in the A() constructor
is handled by the function defined in B, but before B's initializer or constructor has had a chance to set the values of x and y in B.
So we see that it is possible to call methods on an object before it is completely constructed, by calling it's methods in the superclass constructor.
I seem to recall my java instructor in college warning us about situations like that...
[ January 17, 2004: Message edited by: Phil Rhodes ]
 
Phil Rhodes
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's an enhanced version that shows explicitly that B.PrintFields
occurs before even the instance initializer in B executes:
class A
{
public A()
{
System.out.println( "in A() ctor" );
PrintFields();
}
public void PrintFields()
{
System.out.println( "in A.PrintFields()" );
}
}
class B extends A
{
int x = 1;
int y;
{
System.out.println( "in B's instance initializer" );
}
public B()
{
System.out.println( "in B() ctor" );
y = -1;
}
public void PrintFields()
{
System.out.println( "in B.PrintFields" );
System.out.println("x = "+x+" y = "+y);
}
}
class Test
{
public static void main(String[] args)
{
B b = new B();
}
}
Run this and you'll get:
in A() ctor
in B.PrintFields
x = 0 y = 0
in B's instance initializer
in B() ctor
HTH...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic