DEV Community

jzfrank
jzfrank

Posted on

final keyword in java explained in 2 mins

In Java, final is an access modifier. It could be used to modify:

final for class

class: this means the class cannot be inherited by subclasses.

public final class Dog extends Animal { // code } 
Enter fullscreen mode Exit fullscreen mode

final for method

method: this means the method cannot be overwritten by subclasses. Use this if you want this method to be non-modifiable by subclasses.

public class Aminal { // other code public final eat() { // code } } 
Enter fullscreen mode Exit fullscreen mode

final for variable

variable: this means the variable can only be assigned once. Use this when you want a constant variable. Typical usage is like

final double PI = 3.14159; 
Enter fullscreen mode Exit fullscreen mode

Also, we remark that Math.PI is a built-in constant variable declared using final. Math is a build-in final class that cannot be inherited.

A peek to the Math class:

public final class Math { /** * Don't let anyone instantiate this class. */ private Math() {} /** * The {@code double} value that is closer than any other to * <i>e</i>, the base of the natural logarithms. */ public static final double E = 2.7182818284590452354; /** * The {@code double} value that is closer than any other to * <i>pi</i>, the ratio of the circumference of a circle to its * diameter. */ public static final double PI = 3.14159265358979323846; // ... other code ...  
Enter fullscreen mode Exit fullscreen mode

reference

code with John

Top comments (0)