1.

This keyword in Java

Answer»

The this keyword in Java refers to the CURRENT object and so is a reference variable. Some of the uses of the this keyword is GIVEN as follows:

  1. The current class object can be pointed to by using the this keyword.
  2. The this keyword can be used in a constructor call as an argument.
  3. The current class constructor can be invoked using this().
  4. The current class method can be invoked implicitly using this keyword.
  5. The this keyword can be used in a method call as an argument.

A program that demonstrates this keyword in Java is given as follows:

class Employee{      int empNo;      String name;      int SALARY;      Employee(int empNo, String name, int salary)    {        this.empNo = empNo;          this.name = name;          this.salary = salary;      }    void print()    {        System.out.println("Employee Number = " + empNo);        System.out.println("Name = " + name);        System.out.println("Salary = " + salary);    } }   public class Demo {      public STATIC void main(String args[])    {        Employee emp1 = new Employee(1, "Amy", 20000);          Employee emp2 = new Employee(2, "Harry", 15000);        Employee emp3 = new Employee(3, "Peter", 50000);        emp1.print();          emp2.print();          emp3.print();      } }

The output of the above program is as follows:

Employee Number = 1 Name = Amy Salary = 20000 Employee Number = 2 Name = Harry Salary = 15000 Employee Number = 3 Name = Peter Salary = 50000


Discussion

No Comment Found