Friday, 25 November 2016

Demonstrate use of 'this' keyword

In java, this is a reference variable that refers to the current object. Java uses this keyword for following:
  1. this keyword can be used to refer current class instance variable.
  2. It can be used to invoke current class method (implicitly)
  3. It can be passed as an argument in the method call.
  4. It can be passed as argument in the constructor call.
  5. 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.

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;
 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);
C:\>java Circle
x = 1.0
y = 3.0
r = 2.5
numCircle = 3

1 comment: