Can someone please help explain the following behaviour, or point me
to a post that explains it?
While i was debugging one of my company's programs i noticed some
objects behaving strangely. I was having a very difficult time
finding the source of the problem. Finally, when i realized what was
going on i wrote the following three classes to try to understand what
happens in the JVM.
Given:
/**
* @author Ashkon Sabet
* www.ashkon.net
*/
public class Parent
{
protected boolean parentBoolean = false;
public Parent()
{
System.out.println("Entering Parent() Constructor");
init();
System.out.println("Exiting Parent() Constructor");
}
protected void init()
{
System.out.println("Entering Parent.init()");
parentBoolean = true;
System.out.println("Value of parentBool "+parentBoolean);
System.out.println("Exiting Parent.init()");
}
}
/**
* @author Ashkon Sabet
* www.ashkon.net
*/
public class Child extends Parent
{
protected boolean childBoolean = false;
public Child()
{
super();
}
protected void init()
{
System.out.println("Entering Child.init()");
super.init();
setChildBoolean();
System.out.println("Child.childBoolean = "+childBoolean);
System.out.println("Exiting Child.init()");
}
public void setChildBoolean()
{
if (super.parentBoolean == true)
this.childBoolean = true;
}
}
/**
*
* @author Ashkon Sabet
* www.ashkon.net
*/
public class FamilyTester {
/** Creates a new instance of FamilyTester */
public FamilyTester() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
Child myFirstChild = new Child();
System.out.println("My First Child Boolean ==
"+myFirstChild.childBoolean);
// Child mySecondChild = new Child();
// mySecondChild.setChildBoolean();
// System.out.println("My Second Child Boolean ==
"+mySecondChild.childBoolean);
}
}
When you run FamilyTester you get the following output:
Entering Parent() Constructor
Entering Child.init()
Entering Parent.init()
Value of parentBool true
Exiting Parent.init()
Child.childBoolean = true
Exiting Child.init()
Exiting Parent() Constructor
My First Child Boolean == false
*******************************
I would have expected the last line to read:
My First Child Boolean == true
Thank you for you help.
-Ash