0

Which is preferable Sample.this.display() or this.display()?

 class Sample{

 void display(){
  System.out.println("display() called");
 }

 void callDisplay(){
  Sample.this.display();  // 1
  this.display();   // 2
 }

 public static void main(String args[]){      
  Sample s = new Sample();
  s.callDisplay();      
 }
}
  1. Can You explain the difference?
  2. Which is better choice?
  3. Is there any special meaning/purpose for Sample.this.display()?
user992782
  • 17
  • 4

3 Answers3

4

The reason you could use the classname like Sample.this.display() is when you are in an inner class and you want to reference this of an enclosing class. In the example provided, it makes no difference.

Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57
0

i would go for 3

 void callDisplay(){
  display();  // 3  
 }

dont think there is a real difference but all the extra this and Sample.this only add non needed code so i would not use them at all

unlike

 private String something;
 void setSomthing(String something){
     this.something = something;
 }

where it is absolutely needed

Peter
  • 5,728
  • 20
  • 23
0

You are calling from same class, you don't need both. Simple display() should be enough.

kosa
  • 65,990
  • 13
  • 130
  • 167