Jump to content
Wikibooks The Free Textbook Project

Java Programming/Keywords/this

From Wikibooks, open books for an open world

this is a Java keyword. It contains the current object reference.

  1. Solves ambiguity between instance variables and parameters .
  2. Used to pass current object as a parameter to another method .

Syntax:

this .method();
or
this .variable;

Example #1 for case 1:

Computer code
publicclass MyClass
{
//...
privateStringvalue;
//...
publicvoidsetMemberVar(Stringvalue)
{
this.value=value;
}
}

Example #2 for case 1:

Computer code
publicclass MyClass
{
MyClass(inta,intb){
System.out.println("int a: "+a);
System.out.println("int b: "+b);
}
MyClass(inta){
this(a,0);
}
//...
publicstaticvoidmain(String[]args){
newMyClass(1,2);
newMyClass(5);
}
}

AltStyle によって変換されたページ (->オリジナル) /