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();
}
}
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.
Q) Is final method inherited? Ans) Yes, final method is inherited but you cannot override it.
What cannot be inherited ? Constructors. Although, the subclass constructor has to call the superclass constructor if its defined (More on that later!) Multiple classes.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With