Learn final method in java with example and explanation.

In a class, we make a method final so that no child class can override and implement it.

NOTE: If a class is having final method, it does not mean that the class is also a final class. Purpose of final method is only that it cannot be overridden in child class.

Prerequisite: method overriding in java and java inheritance concept .

You can make many methods final in a class, whom you want that no sub classes should override and implement them.

Final Methods can’t be overridden

Example of final method in java

Below, class X has a final method m1(). If we try to override and implement in a sub class Y in below java code, then compiler will flash an error.

class X {

	// final method
	final public void m1() {

	}

	public void m2() {

	}

}

// Sub class /derived class
class Y extends X {
	// We cannot override base class X method m1() but m2()
	@override
	public void m2() {

	}
}

Related Posts