hye juan, for all the instances that you create of a class, will have its own set of instance variables that you define. In the first example you set the String in test1 to "Hello" but not String of test2. so you will be getting null/
In the second example, you are passing the f1 as a parameter to the constructor of f2. Where you are actually setting the value of f1's x to 8. Hence you get an 8
Juan Manuel Alberto de los Santos
Joined: Jun 26, 2008
the constructor uses f1 object reference and changes the x value to 8
in f2 the reference is simply pointed to the original x, that's why is 5
... i don't know if it's correct, is kind of hard to understand
We are not considering the value of f2's x here in this case.
The new Fizz object that you create in the constructor is actually a reference to the original f1 object. So the initial value for f1's x is 5 and now you are changing the value to 8 with in the constructor of f2.
You have decalred a no-argument constructor and an overloaded constructor which takes a String as an argument. Thus whenever you call new on an instance of the class, the constructor will either run with the no-argument constructor which initializes nothing, or it takes a string which returns initializes the String variable to the value "Hello".
Since you are calling your print function on test2.s, test2 is a new instance of test in which you have not pased a String variable, and thus the instance will initialize the test2 instance using the no-argument constructor. Therefore s has not been initialized by you with any value and thus gets a null from the JVM.
If you had done the same with an int you would get 0, a boolean, false and so on.
[ October 03, 2008: Message edited by: Stephen Davies ]
be a well encapsulated person, don't expose your privates, unless you public void getWife()!
subject: null instance variable after assigning a value