What is the use of ?this??

Answer Posted / ranganathkini

The 'this' keyword in Java has the following uses:

1. To resolve ambiguity where a local variable hides a class
member. Example:

class MyClass {
private int value;

public MyClass( int value ) {
// local variable 'value' hides class field 'value'
this.value = value;
}
}

2. To invoke one constructor overload from another. Example:

class MyClass {
private int value;

public MyClass( int value ) {
this.value = value;
}

public MyClass() {
// invoke MyClass( int value )
this( 0 );
}
}

3. To pass the current object instance as a parameter to a
method. Example:

class MyClass {
private int value;

public MyClass( int value ) {
this.value = value;
// pass current instance as a parameter to the method
displayValue( this );
}

public static void displayValue( MyClass mc ) {
System.out.println( "Value = " + mc.value );
}
}

4. To invoke an outer class's non-static method from a
non-static inner class. Example:

class MyOuterClass {

class MyInnerClass {
public MyInnerClass() {
// call the outer class's method
MyOuterClass.this.displayText( "Inner instance
created" );
}
}

public void displayText( String text ) {
System.out.println( text );
}
}

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why stringbuilder is not thread safe in java?

566


Can we catch more than one exception in single catch block?

599


What is the difference between equals() and?

583


I want to persist data of objects for later use. What is the best approach to do so?

589


Is space a char?

524






What is abstract class constructor called?

563


What is the difference between yield() and sleep()?

539


How a variable is stored in memory?

497


What is linkedlist in java?

502


What does the string method compareto () do?

535


Explain scope or life time of local variables in java?

557


Are registers volatile?

529


What is starvation?

679


What is tostring () method?

540


What is garbage collector?

618