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.


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

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative