iT Portal

A java program using this Keyword !!!

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Constructors use this to refer to another constructor in the same class with a different parameter list.

Whenever we are creating an object, the copies of the instance variables are created for each object

Using this keyword with constructors :
For example,

class ThisDemo1
int a = 0;
int b = 0;
ThisDemo1(int x, int y)
this.a = x;
this.b = y;
public static void main(String [] args)
ThisDemo1 td = new ThisDemo1(10,12);
ThisDemo1 td1 = new ThisDemo1(100,23);
System.out.println(td.a); // prints 10
System.out.println(td.B); // prints 12
System.out.println(td1.a);// prints 100
System.out.println(td1.B);// prints 23

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: