Menu Close

this keyword in java

this:

  • It is a keyword
  • It is a pre-defined variable
  • It holds object address
  • It must be used inside non static area

Displays address using ‘this’:

class Test 
{
	Test() // non static
	{
		System.out.println("In constructor : " + this);
	}
	public static void main(String[] args) 
	{
		new Test();
	}
}

How to access object address:

  • In non static context: using ‘this’
  • In static context: using ‘object reference variable’
class Test 
{
	Test()
	{
		System.out.println("In constructor : " + this);
	}
	public static void main(String[] args) 
	{
		Test obj = new Test();
		// System.out.println("In main : " + this);  -> Error : 'this' not allowed in static
		System.out.println("In main : " + obj);
	}
}

Accessing static members:

  • We access static members (variables or methods) using class name
  • From any location (static or non static) we using class name
  • For example..
class Test 
{
	Test()
	{
		System.out.println("From constructor : ");
		Test.fun();
	}
	public static void main(String[] args) 
	{
		Test obj = new Test();
		System.out.println("From main");
		Test.fun();
	}
	static void fun()
	{
		System.out.println("static fun..");
	}
}

How can we access non static members?

  • Generally non static members need to access using object address
  • From non static area, we use ‘this’ variable
  • From static area, we use ‘object reference variable’
class Test 
{
	Test()
	{
		System.out.println("From constructor : ");
		this.fun();
	}
	public static void main(String[] args) 
	{
		Test obj = new Test();
		System.out.println("From main");
		obj.fun();
	}
	void fun()
	{
		System.out.println("static fun..");
	}
}

Check this out:

class Test 
{
	public static void main(String[] args) 
	{
		Test obj = new Test();
		System.out.println("Main");
		obj.m1();
	}
	void m1()
	{
		System.out.println("m1");
		this.m2();
	}
	void m2()
	{
		System.out.println("m2");
		Test.m3();
	}
	static void m3()
	{
		System.out.println("m3");
	}
}