What is the use of ?this??

Answers were Sorted based on User's Feedback



What is the use of ?this??..

Answer / 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

What is the use of ?this??..

Answer / ashokmail

'this' operator is used to denote the current working
object.

EX:
Class student{
public student(){
this.addStudent();
}
public void addStudent(){
// to do code here
}
public static void main(String args[]){
new student();
}
}

'this' in the constructor is used to denote the current
working object student...

Is This Answer Correct ?    0 Yes 0 No

What is the use of ?this??..

Answer / ravikiran

this is used to refer the current instance

Is This Answer Correct ?    0 Yes 0 No

What is the use of ?this??..

Answer / vijayakumar chinnasamy

this:
a. It call the overloaded(same class only)constructor
b.refer the current object.
c.U cant use 'this' in static method.

Is This Answer Correct ?    0 Yes 1 No

Post New Answer

More Core Java Interview Questions

How many objects are created for a singleton class

7 Answers   Ness Technologies,


Can an object be null?

0 Answers  


How you can force the garbage collection?

0 Answers  


What is meant by event handling?

2 Answers  


What are the limitations for static method?

3 Answers   Greenwood,






How do you avoid global variables?

0 Answers  


Which method you will use to create a new file to store some log data. Each time a new log entry is necessary, write string to the file in java ?

0 Answers   HCL,


What is the map interface in java programming?

0 Answers  


What is OOP?

2 Answers   BMC, Microsoft,


how to minimize the functionality to will not force garbage collector?

2 Answers  


What is difference between final and immutable?

0 Answers  


Can you start a thread twice in Java?

0 Answers  


Categories