• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference b/w class.this.var and ((class)this).var

 
neeta mathur
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
can anyone tell me the difference between acessing hidden variable and accesing variable from outer class.
in the following program--when i access outer variable as test.this.s(in line 5) --compiles fine--but when i access the same hidden variable as ((test)this).s i get compile error

WHEN DO WE EXACTLY USE (test)this).s FORMAT (to access hidden vars) AND HOW???

public class test {
final String s="outer";
class Inner {
String s="inner";
public void m1() { System.out.println(((test)this).s); }//line 5
}//inner
public void m() { System.out.println("in outer");}//m()
public static void main(String args[]){
test o = new test();
o.new Inner().m1();
}
}
NEETA
 
Stefan Guilhen
Ranch Hand
Posts: 61
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do you are saying the following: "take the reference to this inner class object, cast it to test and then try to access the s field". But notice that you cannot cast this to test in the code you provided, because this is a reference to the inner class and you cannot cast it to be a reference to the outer class.

When you do you are actually accessing the field s using a reference to the actual outer class object and this is fine. What you are saying when you do that is: "Take the reference to the outer class object and try to access the field s using that reference".

Hope that helps
Stefan
[ August 31, 2004: Message edited by: Stefan Guilhen ]
 
neeta mathur
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it--it must be used only when there is an "is-a" relationship
Thank u stephen
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic