Final Modifier (Class, Method, Variable) in Java

final modifier in java

Final Modifier (Class, Method, Variable) in Java

final is a keyword modifier in java. It is applicable for the class, method and variable. Everything about final keyword is explained here with the help of examples. So let’s understand the final modifier.

Usage of Final Modifier

Also Read: Difference between Break and Continue statement in java

Also Read: Java program to count number of vowels in a sentence

1) Final with Variable :-

We can declare a variable in java with the help of final modifier. If we declare variable as final then we can not change it’s value. In short we can say that it is used to declare constant in java.

Ex.

class FinalDemo
{
   final int x = 10;
   x++; //can not modify it's value now.
}

In above example we will get compile time error because we increment the value of x (modify) and which is declared as final.

If the instance variable is declared as final then we have to perform initialization explicitly whether we are using it or not. And JVM will not provide any default value.

 

2) Final with Method :-

If the parent class method is declared as final then we can not override that method in the child class. Because it implemented as final.

Ex.

class Parent
 {
   public final void m1()
   {
     System.out.println("This is parent class final method.");
   }
}

class Child extends Parent
{
  public final void m1() //overide
  {
    System.out.println("This is child class final method.");
  }
}

In above example we will get compile time error because we override parent class final method ( m1() ) in child class. It means If we declare any parent class method as final then it can available to the child class but we can not override or redefine that method.

3) Final with Class :-

If we declared any class as final than we can not extend features of that class. It means we can not create child class for that class. And inheritance feature is not possible for that class.

Ex.

final class Parent
{
}
class Child extends Parent
{
}

In above example we will get compile time error because we declared Parent class as final. So now we can not extend Parent class to any other class.

Note :- If any class is declared as final than all methods present inside that class is by default become final. But variable present inside final need not to be final.

The main advantage of final keyword is we can achieve security and we can provide unique implementation. And main disadvantage of final keyword is we are missing key features of OOPs : Inheritance(because of final class) and Polymorphism(because of final method).

Thank You ! 🙂

Stay Connected with PLace4Java and follow us on our Facebook Page.

Be the first to comment

Leave a Reply

Your email address will not be published.


*