Java program – how to use “this” keyword?

Here is a Java program that helps you to understand the concepts of “this” keyword in Java. Type, compile and run to understand how to use the concepts and features of “this” in a Java program.

Also, note the overall structure of a set of java classes. (4 Java classes are used in this single java program)

Java program to show different uses of “this” keyword

/*
Learn Usage of “this”,
Also note the overall structure of a set of java classes
*/

class A
{
int a,b;
void setVal(int c,int d)
{a=c;
b=d;
}
void getVal()
{
System.out.println(“\nA=”+a);
System.out.println(“B=”+b);
}
}
class A1
{
int a,b;
void setVal(int a,int b)
{a=a;//incorrect implementation, will compile, but at runtime will give unwanted o/p
b=b;
}
void getVal()
{
System.out.println(“\nA=”+a);
System.out.println(“B=”+b);
}
}
class A2
{
int a,b;
void setVal(int a,int b)
{this.a=a;//will compile and run properly
this.b=b;
}
void getVal()
{
System.out.println(“\nA=”+a);
System.out.println(“B=”+b);
}
}
class B
{
public static void main(String args[])
{
System.out.println(“entering B main”);
A obj1=new A();
obj1.setVal(2,3);
obj1.getVal();

A1 obj2=new A1();
obj2.setVal(4,5);
obj2.getVal();

A2 obj3=new A2();
obj3.setVal(4,5);
obj3.getVal();
System.out.println(“exiting B main”);

}
}

Java program – how to use “this” keyword?
Scroll to top
error: physicsTeacher.in