Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a final class be inherited, but a final method can be inherited?

I have a big confusion in the usage of the "final" keyword between classes and methods. I.e., why do final methods only support inheritance, but not final classes?

final class A{
    void print(){System.out.println("Hello, World!");}
}

class Final extends A{
      public static void main(String[] args){
        System.out.println("hello world");
       }
}

ERROR:

cannot inherit from Final A class Final extennds A{ FINAL METHOD IS..

class Bike{
    final void run(){System.out.println("run");}
}

class Honda extends Bike{
    public static void main(String[] args){
        Honda h=new Honda();
        h.run();
    }
}
like image 497
sravani.s Avatar asked Feb 17 '16 13:02

sravani.s


People also ask

Why final method can be inherited?

final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes.

Can a class with final method be inherited?

Q) Is final method inherited? Ans) Yes, final method is inherited but you cannot override it.

Which method of a class Cannot be inherited?

What cannot be inherited ? Constructors. Although, the subclass constructor has to call the superclass constructor if its defined (More on that later!) Multiple classes.

Why we can override final method in Java?

Can We Override a Final Method? No, the Methods that are declared as final cannot be Overridden or hidden. For this very reason, a method must be declared as final only when we're sure that it is complete.


1 Answers

Why can't a final class be inherited, but a final method can be inherited?

Why? Because final means different things for classes and methods.

Why does it mean different things? Because that is how the Java language designers chose to design the language!

There are three distinct meanings for the final keyword in Java.

  • A final class cannot be extended.

  • A final method cannot be overridden.

  • A final variable cannot be assigned to after it has been initialized.

Why did they decide to use final to mean different things in different contexts? Probably so that they didn't need to reserve 2 or 3 distinct keywords. (In hindsight, that might not have been the best decision. However that is debatable ... and debating it is probably a waste of time.)

It is worth noting that other keywords have multiple meanings in Java; e.g., static and default (in Java 8).

like image 94
Stephen C Avatar answered Sep 29 '22 22:09

Stephen C