final keyword in java

It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance. It is used at variable level, method level and class level.

  In java language final keyword can be used in following way.

  Final at variable level

  Final at method level

  Final at class level


1) final at variable level

final keyword is used to make any variable constant. If you make any variable as final, you cannot change the value of final variable(It will be constant).

class FinalTest {
	public static void main(String arr[]) {
		final int a = 500;//creating local variable final
		 a = 6000;//changing the value
		System.out.println("value of final a =" + a);
	}
}
comileTime error saying....
cannot assign a value to final variable a
a=6000;

2) final at method level

It makes a method final, meaning that sub classes can not override this method.we will get compile time error if try to override the final method.

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

}

class Child extends Parent {
	// trying to override final method m1()
	public void m1() {
		System.out.println("Child m1()");
	}
}
comileTime error saying....
 m1() in Child cannot override m1() in Parent
public void m1()
            ^
overridden method is final

3) Final at class level

If we make any class final then that the class can not be inheriting by other classes . It can not have any child class. final is basically used to restrict inheritance.

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

}

class Child extends Parent {
	public void m2() {
		System.out.println("Child m2()");
	}
}
compileTime Error saying...
cannot inherit from final Parent
class Child extends Parent{
                    ^
1 error
woman avatar