Java this keyword.

this: is called as reference variable because it always refer an current object.

Eg:
Is this valid ?
public class MleClass{
int value=10;
 void show(){
 System.out.println(value);
 }

 public static void main(){
  MleClass obj =new MleClass();
  ob.show();
 }
}

Obj is local variable i.e we can't access that variable outside main method.

In above code snippet value is a instance variable.

So we must need  an object or object or object reference to access value;

Then still valid the above snippet ?


 - Yes, it is valid.
When we call the show with object reference JVM calls the value with current object i.e this
void show(){
  System.out.println(this.value); // JVM internally adds the reference this.
 }

Eg:

public class MleClass{
int value=10;
 void show(){
 int value =100;
 System.out.println(value);
// Here we need this explicitly.
 System.out.println(this.value);
 }

 public static void main(){
  MleClass obj =new MleClass();
  ob.show();
 }
}


this constructor:

Can we have more then one constructor in same class ?
- Yes, we can have with different parameters.

public class MleClass{
  MleClass(){

  }
  MleClass(String param){

  }

}

How do we call same class constructor from another constructor in a class?
- Using this parameter constructor we can call.
But rule is this statement must be the first statement in a constructor other wise compile time error will come.
Why?

Because JVM internally call the super class constructor from every constructor.
So, this statement must be first statement in a constructor.


Eg:
public class MleClass{
  MleClass(){
  // If we don't put this statement her JVM calls the super class constructor with super().
   this("There?"); 
  }
  MleClass(String param){
  System.out.println("Yes, I'm here!");
  }
}

No comments:

Post a Comment