
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using final Keyword to Prevent Overriding in Java
Method overriding can be prevented by using the final keyword with a method. In other words, a final method cannot be overridden.
A program that demonstrates this is given as follows:
Example
class A { int a = 8; final void print() { System.out.println("Value of a: " + a); } } class B extends A { int b = 3; void print() { System.out.println("Value of b: " + b); } } public class Demo { public static void main(String args[]) { B obj = new B(); obj.print(); } }
The above program generates an error as the method print() in class A is final and so it cannot be overridden by the method print() in class B. The error message is as follows:
Demo.java:15: error: print() in B cannot override print() in A
Advertisements