Website For Developers

this keyword in Java



Example without this Keyword in Java

public class WithoutThis {

   String name;
   // Constructor
   WithoutThis (String name) {
     name = name;
   }
   void show () {
     System.out.println (name);
   }

   public static void main (String [] args) {
     WithoutThis obj = new WithoutThis ( "onlineprogramminghub.com" );
     obj.show ();
   }
}

Output

null



Example with this keyword in Java

public class ThisKeyword {

   String name;
   // Constructor
   ThisKeyword (String name) {
     this.name = name;
   }
   void show () {
     System.out.println (name);
   }

   public static void main (String [] args) {
     ThisKeyword obj = new ThisKeyword ( "onlineprogramminghub.com" );
     obj.show ();
   }
}

Output

Note:
Constructors cannot be called in any method other than a constructor.
Only one constructor can be called within a constructor.


Example: this() for default constructor

class ThisConstructor {
   String name;
   // default constructor
   ThisConstructor () {
     System.out.print( "For learning Java, visit: ");
   }
   ThisConstructor (String name) {
     this(); // invoked default constructor.
     this.name = name;
   }
   void show () {
     System.out.println (name);
   }
   public static void main (String [] args) {
     ThisConstructor obj = new ThisConstructor ( "http://onlineprogramminghub.com/" );
     obj.show ();
   }
}

Output

For learning Java, visit: http://onlineprogramminghub.com/