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

What is the difference between equals() and == in java?

662


What is the major difference between linkedlist and arraylist?

665


What is variable and example?

690


What is the final blank variable?

749


Is treeset sorted in java?

738






What is a wrapper method?

717


What is ordered map in java?

724


what is ststic with example

1768


What is sortedmap in java?

731


Can you explain the final method modifier?

743


What are the types of arrays in java?

772


What is primitive data type in java?

700


Is simpledateformat safe to use in the multithreaded program?

700


Which package is used for pattern matching with regular expressions?

812


How can you avoid serialization in child class if the base class is implementing the serializable interface?

798