What are all the ways keyword ‘this’ can be used in Java?

Java 8Object Oriented ProgrammingProgramming

You can use this keyword to –

  • Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
class Student {
   int age;
   Student(int age) {
      this.age = age;
   }
}
  • Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Student {
   int age
   Student() {
      this(20);
   }
   Student(int age) {
      this.age = age;
   }
}
raja
Published on 12-Feb-2018 10:22:37
Advertisements