Issue
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();
}
}
Solution
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 IMO a waste of time.)
It is worth noting that other keywords have multiple meanings in Java; e.g., static
and default
(in Java 8).
Answered By - Stephen C Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.