A method in Java can be declared final using the final keyword. A final method cannot be
overridden. You might make a method fi nal if it has a critical implementation that should
not be changed, or you might just want a child class not to have the option of overriding
a particular method. Whatever the motivation, an attempt to override a final method
generates a compiler error.
The following Lion class has a final method named breathe :
1. public class Lion {
2. public void eat(String something) {
3. System.out.println(“Lion is eating”);
4. }
Declaring Methods 137
5.overridden. You might make a method fi nal if it has a critical implementation that should
not be changed, or you might just want a child class not to have the option of overriding
a particular method. Whatever the motivation, an attempt to override a final method
generates a compiler error.
The following Lion class has a final method named breathe :
1. public class Lion {
2. public void eat(String something) {
3. System.out.println(“Lion is eating”);
4. }
Declaring Methods 137
6. public final void breathe() {
7. System.out.println(“Lion is breathing”);
8. }
9. }
No subclass of Lion can override the breathe method, but let ’ s try it anyway and see
what happens. The following MountainLion class extends Lion and declares a breathe
method:
1. public class MountainLion extends Lion {
2. public void breathe() {
3. System.out.println(“MountainLion is breathing”);
4. }
5. }
As expected, this does not compile. Here is the compiler error that it generates:
MountainLion.java:2: breathe() in MountainLion cannot override breathe() in
Lion; overridden method is final
public void breathe() { }
No comments:
Post a Comment