public class Test026 { static Test026 t = new Test026(); String str; public static void main(String args[]) { Test026 t = new Test026(); t.method("0"); } void method(String str) { str = str; System.out.println(str); System.out.println(t.str); System.out.println(this.str); } }
The output is: 0 null null I didnt really understand why ? can somebody hlep. this is a queation from jiris mock #2
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
posted
0
Because str = str does not assign the value of the parameter str to the member str but to itself. The result you were expecting can be obtained by replacing str = str with this.str = str The method parameter str shadows the instance member called str. [ September 12, 2002: Message edited by: Valentin Crettaz ]
why is the 2nd and 3rd output null ? I am confused
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
posted
0
Because the string literal "0" passed as parameter to method() is never assigned to the member called str of the Test026 class. When entering method(), the str parameter's value is reassigned to itself and not to the member that has the same name. This example shows that it can be dangerous to give member fields and method parameters the same name and that if this is the case, the member should be qualified with "this." so that there is no ambiguity. [ September 12, 2002: Message edited by: Valentin Crettaz ]
Barkat Mardhani
Ranch Hand
Joined: Aug 05, 2002
Posts: 787
posted
0
Q1. I am little confused by line 1. It seems like that this statement is trying to define a member object for this class. So far I have seen that this member object is an object of another class to provide for what is called composition. But in this case it is defining a member object which is an object of its own clas!!! Q2. Refer to line 2. Within the backdrop of having a member object named t, would it not be ambiguise to create a new object of this class referred to as t. So if I have to refer to member object t of object t, would I say: t.t
Vin Kris
Ranch Hand
Joined: Jun 17, 2002
Posts: 154
posted
0
1) This too is composition... or aggregation if you want it call it. Example: Linked List This code presents an interesting scene. The method can be invoked as follows public static void main(String args) { Test026.t.t.t.t.t.t.t.method("0"); } Any number of t's could be placed... but they all refer to the same static object. 2) you could also refer to it as Test026.t, in fact better this way. [ September 12, 2002: Message edited by: Vin Kris ]