java final modifier code example

Example 1: what it means when create final variable in java

First of all, final is a non-access modifier applicable only to 
a variable, a method or a class

When a variable is declared with final keyword, its value can’t be modified, 
essentially, a constant. This also means that you must initialize a 
final variable. If the final variable is a reference, this means that 
the variable cannot be re-bound to reference another object, but internal 
state of the object pointed by that reference variable can be changed 
i.e. you can add or remove elements from final array or final collection. 
  It is good practice to represent final variables in all uppercase, using 
  underscore to separate words.

Example 2: java final meaning

private final String hello = "Hello World!";
/*
The keyword final states that the variable, method or class
associated will not have it's value changed.
*/

Example 3: What is final access modifier in java

final access modifier can be used for class, method and variables. 
The main advantage of final access modifier is security no one can modify 
our classes, variables and methods. 
The main disadvantage of final access modifier is we cannot implement 
oops concepts in java. 
Ex : Inheritance, polymorphism.
final class : A final class cannot be extended or subclassed. 
We are preventing inheritance by marking a class as final. But we can still 
access the methods of this class by composition. 
Ex: String class
final methods: Method overriding is one of the important features in java. 
But there are situations where we may not want to use this feature. 
Then we declared method as final which will print overriding. To allow a method 
from being overridden we use final access modifier for methods.
final variables : If a variable is declared as final ,it behaves like 
a constant . We cannot modify the value of final variable. Any attempt 
to modify the final variable results in compilation error. The error is like
“final variable cannot be assigned.

Example 4: java final modifier on method

public class Shape {
  private int numberOfVertices;
  
  //with final modifier,
  //this method cannot be overridden by subclasses
  public final int getNumberOfVertices() {
    return numberOfVertices;
  }
}

Example 5: how make a final variable in java

class scratch{
	public static void main(String[] args){
		final pi = 3.14;
	}
}

Tags:

Java Example