Preventing Overriding in Java

By | August 24, 2012

Methods and variables can be ‘override’ in subclasses. (Yes, it’s a good

feature too!). But what if we don’t want to ‘override’ our Methods and Variables in Java?

It’s simple…

Declare them using the keyword ‘final’ as modifier. That’s it.

eg:

final int myVariable = 79;

So the value of myVariable can never be changed any way.

Also for Classes/Methods.

eg:

final class myClass{ whatever your code;} 

It will prevent our myClass being extended.

Leave a Reply

Your email address will not be published. Required fields are marked *