Demonstrate use of 'this' keyword
In java, this is a reference variable that refers to the current object. Java uses this keyword for following:
- this keyword can be used to refer current class instance variable.
- It can be used to invoke current class method (implicitly)
- It can be passed as an argument in the method call.
- It can be passed as argument in the constructor call.
- It can also be used to return the current class instance.
In this program, we have used static keyword. The output of program is the number of objects created during program execution and it will display values of x, y, z for c1 object.
PROGRAM
PROGRAM
public class Circle {
public static int numCircle=0;
double x,y,r;
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
numCircle++;
}
public static void main(String[] args) {
Circle c1 = new Circle(1.0,3.0,2.5);
Circle c2 = new Circle(1.0,3.0,2.5);
Circle c3 = new Circle(1.0,3.0,2.5);
System.out.println("x = "+c1.x);
System.out.println("y = "+c1.y);
System.out.println("r = "+c1.r);
System.out.println("numCircle = "+numCircle);
}
}
OUTPUT
C:\>javac Circle.java C:\>java Circle x = 1.0 y = 3.0 r = 2.5 numCircle = 3