Java - Inheritance and final


You can disable subclassing for a class by declaring the class final.

A final class cannot be subclassed.

final class

The following snippet of code declares a final class named S:

public final class S{

The following declaration of class will not compile:

// Won't compile. Cannot inherit from S
public final class C extends S{

final method

You can declare a method as final.

A final method cannot be overridden or hidden by a subclass.


class A {
  public final void m1() {
  }/*w  w w. j  a v a2 s  . com*/

  public void m2() {

class B extends A {
  // Cannot override A.m1() here because it is final in class A
  // OK to override m2() because it is not final in class A
  public void m2() {
    // Code goes here