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

Can you make a constructor final in Java?

724


What is a parent class in java?

632


What is the meaning of nullable?

661


What is a substring of a string?

648


What is the difference between the ">>" and " >>>" operators in java?

605






What are different exception types exceptions available in java ?

588


What is maximum size of arraylist in java?

579


What will be the output of round(3.7) and ceil(3.7)?

768


What is method in research paper?

670


What are the differences between Java 1.0 and Java 2.0?

1754


Explain methods specific to list interface?

643


What is a methodologist?

644


what are synchronized methods and synchronized statements? : Java thread

660


What is one third plus one third as a fraction?

570


What is the difference between variable & constant?

630