Page 377 - Computer_Science_F5
P. 377
Computer Science Java program to demonstrate final keyword to final method
Program Example 5.32:
class FinalClass {
// code that creates a final method
FOR ONLINE READING ONLY
public final void show() {
System.out.println(“This is a final method.”);
}
}
class Main extends FinalClass {
// Uncommenting the following method will cause a compilation error
// because you cannot override a final method
/*
public final void show() {
System.out.println(“Trying to override final method???.”);
}
*/
public static void main(String[] args) {
Main myObj = new Main();
myObj.show(); // This will call the show() method from FinalClass
}
}
Output:
Figure 5.34: Output demonstrate final keyword to final method
(iii) Final class
In java, you can declare the class as final in order to restrict other classes to inherit
the parent class. The final class cannot be inherited by another class, as shown in
Program Example 5.33.
Program Example 5.33:
Java program to demonstrate final class
// This code creates a final class
final class FinalClass {
public void show() {
System.out.println(“This shows a final method.”);
}
}
368
for Advanced Secondary Schools
Computer Science Form 5.indd 368 23/07/2024 12:34

