hi all, out put for this below program is 10.can anyone explain this.i saw this quetion in mockexams
public class Honley{ public static int i =60; public static void main(String argv[]){ Honley h = new Honley(); h.wine(); } public void wine(){ i = 10; int i = 20; System.out.println(this.i);
} }
SCJP,SCWCD,IBM 285,MCTS
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
posted
0
In this case, this is irrelevant because the variable is static.
You are simply printing the value of i in the class Honley.
Instance methods can access static members so you set the value of the static member i to 10, and then when you print this.i, the value of the variable i associated with the class Honley is printed.
Pramila Chinguru
Ranch Hand
Joined: May 05, 2006
Posts: 54
posted
0
this.i refers to instance variable. Instance variable i is overridden in wine method to 10, hence 10 is the output. Incase if you print(i), 20 will be the output. since i represents local variable declared in wine method and has the value of 20. Hope it helps.
Ram Han
Ranch Hand
Joined: Feb 26, 2002
Posts: 48
posted
0
thanks i got it
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
posted
0
I wanted to clarify my last remark.
When a static member of a class is referred to using a qualified instance, then it is irrelevant which instance refers to the static member.
The type of the class is what matters.
You create a local variable named i after you modify the static member i.