Understanding This and Final Keywords in Java

Understanding This and Final Keywords in Java

Introduction

Java is a pure object-oriented language. All of the code we write in Java must be inside a class. That’s why Java requires a lot of unique keywords and methods to establish relations and communication between multiple classes.

To implement its object-oriented nature, this and final keywords in Java are used. In this article, we’ll be discussing the various usage of these keywords with the help of examples.

To know more about keywords in Java, refer to this blog, Data Types And Identifier In Java.

Java this Keyword

The keyword this in Java refers to the current instance of the class within a method or constructor. By referring to the current instance, we refer to the object whose methods or constructors are being called.

We can refer to any member of the current instance by using “this”. There are various usage of “this” keywords. Some of them are mentioned below.

  1. To refer to the current class instance variable.
  2. To invoke the current class method and constructor.
  3. Passed as an argument in method or constructor call.
  4. To return the instance of the current class from the method.

Let’s see one by one with an example.

To refer to the current class instance variable

It can refer to the current instance variable of a class inside a method or constructor. There are times when the name of the class attribute and the method or constructor parameters are the same. In such cases, this keyword is used to clear things out.

For example: Let’s see with a comparison.

Without using this keyword
class Employee {
      // class attribute
int emp_no;
String name;

      //constructor parameter are same as class attribute e.g emp_name
Employee(int emp_no, String name) 
{
 emp_no = emp_no;//Ambiguity
 name = name;//Ambiguity
}

void display() 
{
 System.out.println(emp_no + " " + name);
}
}
public class TestThis {
public static void main(String args[]) 
{
 Employee e1 = new Employee(13, "Vaishnavi");
 e1.display();
}
}
Output: 
0 null

In the above example, we can see, the compiler got confused between the class attribute emp_no and constructor argument with the same name. 

Using this keyword
class Employee {
int emp_no;
String name;

Employee(int emp_no, String name) 
{
 //this referring to class attribute here, resolving ambiguity
            this.emp_no = emp_no;
 this.name = name;
}

void display() 
{
 System.out.println(emp_no + " " + name);
}
}
public class TestThis 
{
public static void main(String args[]) 
{
 Employee e1 = new Employee(13, "Vaishnavi");
 e1.display();
}
}
Output: 
13 Vaishnavi

In this case, the “this” keyword has resolved this ambiguity by referring to the class instance.

To invoke the current class method and constructor

Case-1: To invoke the current class method we can use “this” keyword. If we don’t do this, the compiler automatically adds it while calling the class method.

Example:

class Employee {
int emp_no;
String name;

Employee(int emp_no, String name) 
{
 this.emp_no = emp_no;
 this.name = name;
}

void printheader()//The method
{

       System.out.println("The name and employee id of the employee is mentioned above!!");
}

void display() 
{
 System.out.println(this.emp_no + " " + this.name);
 this.printheader();// invoking the method using this keyword
}
}
public class TestThis {
public static void main(String args[]) 
{
 Employee e1 = new Employee(13, "Vaishnavi");
 e1.display();
}
}
Output:
13 Vaishnavi
The name and employee id of the Employee is mentioned above!!

Case 2: We can also use the “this” keyword to call the current class constructor. This is called constructor chaining.

Example: We call a default constructor using the “this” keyword from a parameterised constructor of the same class.

class Employee 
 {
 Employee()//The default constructor
 {  
    System.out.println("Inside Employee class!!");
 }  
 Employee(int data)//Parameterised constructor
 {  
    this();//to call the above default constructor
    System.out.println(data);

}

class TestThis
{  
  public static void main(String args[])
  {  
   Employee a=new Employee(15);  
  }  
}  
Output:
Inside Employee class!!
15

Passed as an argument in method or constructor call

This keyword can also be passed as an argument in the method and the constructor.

Case:1 Passed in a method.

Example: In the example below, method1 is invoked from method2 using the “this” keyword.

class Employee {

void method1(Employee e)//The method 
{
 System.out.println("Method1 is invoked from Method2");  
}

void method2()
{
 method1(this);//Passed as an argument inside a method call
}

}
public class TestThis {
public static void main(String args[]) 
{
 Employee e1 = new Employee();
 e1.method2();
}
}
Output:
Method1 is invoked from Method2

Case:1 Passed in a constructor.

Example: In the example below, “this” keyword is passed in the TestThis class constructor.

class Employee 
 {
 TestThis obj;  
 Employee(TestThis obj)
 {  
    this.obj=obj;  
 }  
  void display()
  {  
    System.out.println(obj.data);//using data member of TestThis class  
  }  
}

class TestThis
{  
  int data=10;  
  TestThis()//Constructor of the class TestThis
  {  
   Employee e=new Employee(this);// this passed as an argument 
   e.display();  
  }  
  public static void main(String args[])
  {  
   TestThis a=new TestThis();  
  }  
}
Output:
10

To return the instance of the current class from the method

This keyword can be returned as a statement from the method. In this case, the method’s return type must be the class type.

Example:

class Employee 
 {
 Employee method1()//Method of class Employee
 {  
    return this;//Returning the instance of the class using this 
 }  
 void method2()
 {  
    System.out.println("Coding Ninjas");

}

class TestThis
{  
  public static void main(String args[])
  {  
   Employee e=new Employee();  
   e.method1().method2();
  }  

Output:
Coding Ninjas

This was all about the “this” keyword in Java. Let’s learn about the final keyword.

The final Keyword in Java

The final keyword in Java is used to apply constraints on variables, methods and classes. The final keyword can be used with classes, methods and variables. Let’s see them one by one.

The final variables in Java

The variables that are declared final in Java become immutable, i.e. their values can’t be changed.

Let’s see, with the help of an example. We’ll make a variable final and try changing its value.

 class Employee 
 {
  final int id = 25;//variable initialised as final
  void printvalue()
  {
   /*
 Trying to change the value of final variable 
 gives compilation error
 */
   id  = 50;
  }
  public static void main(String args[])
  {  
   Employee e=new Employee();  
   e.printvalue();
  }  

Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The final field Employee.id cannot be assigned

at Employee.printvalue(Employee.java:7)
at Employee.main(Employee.java:12)

The final methods in Java

We can declare all or some of the methods of a class as “final”. The methods, once declared final, cannot be overridden by a subclass.

Example:

 class Employee //class with a final method
 {
  final void printvalue() //Method declared as final in Java
  {
   System.out.println("Inside the class employee!!")
  }
 }
 class Test extends Employee //child class
 {
 void printvalue() //trying to override a final method   
        {
   System.out.println("Inside the class Test!!")
  }
 public static void main(String args[])
  {  
 Test e=new Test();  
 e.printvalue();
  }  
 
Output:
Error: LinkageError occurred while loading main class TestThis
java.lang.VerifyError: class Test overrides final method Employee.printvalue()V

The final class in Java

We can also declare an entire class as final. Once a class is declared final, it cannot be subclassed, i.e. we cannot extend it.

Example:

 final class Employee {}//final class in Java
 class Test extends Employee//trying to extend a final class
 {
 void printvalue()
  {
   System.out.println("Inside the class Test!!");
  }
 public static void main(String args[])
  {  
   Test e=new Test();  
   e.printvalue();
  }  
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

at Test.main(TestThis.java:8)

After exploring all about this and final keywords in Java, let’s see some of the frequently asked questions on this topic

Frequently asked questions

What is the final keyword in Java, for example?

The final keyword in Java is used to apply constraints on variables, methods and classes. The final keyword can be used with classes, methods and variables.

What are this and final keywords in Java?

The keyword “this” in Java refers to the current instance of the class within a method or constructor. And the final keyword in Java is used to apply constraints on variables, methods and classes.

What are the final variable and final method in Java?

The variables declared final in Java become immutable, i.e. their values can’t be changed. The methods, once declared final, cannot be overridden by a subclass.

What are the final methods?

The methods that are declared final cannot be overridden by a subclass.

Can a constructor be final?

No, a constructor cannot be declared as final.

Key Takeaways

In this article, we’ve discussed the various usage of this and final keywords in Java with the help of examples. If you want to know more about keywords in Java, you can read this blog, Data Types And Identifier In Java.

To get a command over java programming language, we suggest you practice problems on  Code studio in Java language.

Java is one of the most popular languages. It finds wide applications in Android development and server development. In-depth knowledge of Java will land you a lucrative job. After exploring “this and final keywords in Java,” you can also check out our Guided Path to learn more about a complete, curated preparation guide for coding interviews in tech and product-based companies.

Happy Learning!

Exit mobile version