I have a big confusion in the usage of "final" keyword between classes and methods i.e.why 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();
}
}
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
anddefault
(in Java 8).Final method inheritance only allow access to the final method in child class but overriding is not allowed.