- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you prevent a method from getting overridden in java?
Inheritance can be defined as the process where one (parent/super) class acquires the members (methods and fields) of another (child/sub).
If two classes are related to each other with inheritance. If the super class and sub class contains same methods (same name and arguments), When we invoke this it using the sub class object, the method of the sub class will be executed. This mechanism is known as overriding.
Overriding final methods
Once you declare a method final it cannot be overridden If you try to do so, it generates a compile time error −
Example
class Super{ public final void demo() { System.out.println("This is the method of the superclass"); } } class Sub extends Super{ public final void demo() { System.out.println("This is the method of the subclass"); } }
Compile time error
Sub.java:7: error: demo() in Sub cannot override demo() in Super public final void demo() { ^ overridden method is final 1 error
If you try to compile the same program in eclipse you will get the following error −
Therefore, if you want to prevent a method from being overridden you just need to declare it final.
- Related Articles
- Why You Keep Getting Tonsil Stones and How to Prevent Them
- How do you create a list from a set in Java?
- Can a constructor be overridden in java?
- If a method in parent class “throws Exception”, can we remove it in overridden method in java?
- How do you write a method in Java that can print object in array?
- How many ways to prevent method overriding in Java?
- How do you copy a list in Java?
- How do you create a list in Java?
- How do you make a list iterator in Java?
- How to prevent object of a class from garbage collection in Java?
- What do people do to prevent their cars from rusting?
- Can the overriding method throw the super-type of the exception thrown by the overridden method in Java?
- How do you copy an element from one list to another in Java?
- How do you remove duplicates from a list in Python?
- How do you create a list with values in Java?

Advertisements