Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java basics about final keyword

Can final keyword be used for a method?

like image 225
Abhishek Sanghvi Avatar asked Aug 29 '09 14:08

Abhishek Sanghvi


People also ask

What are the 3 uses of final keyword in java?

What are the three different uses of final keyword in java? Create Constants, prevent inheritance, and prevent methods from being inheritance are the three main uses of final keyword in java.

Why do we use final in Java?

In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can't be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.

What is the use of final keyword on a method?

You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses.


2 Answers

Absolutely! The final keyword can be applied to just about anything, in each case meaning "you don't get to change this anymore."

Here's what it means when applied to...

a variable: You simply cannot assign the variable a new value (rendering it a constant, of course)

a method: You cannot re-implement (i.e., override) this method in a subclass

a class: You cannot define a subclass

In each case we're simply indicating: once this thing is declared, this is the last value (or implementation) you'll ever see for it.

like image 75
VoteyDisciple Avatar answered Oct 04 '22 00:10

VoteyDisciple


Yes, it is possible to declare a method as final. That will mean that a method cannot be overridden by its subclasses.

From The Java Language Specifications, Third Edition, Section 8.4.3.3:

A method can be declared final to prevent subclasses from overriding or hiding it. It is a compile-time error to attempt to override or hide a final method.

For more information, the Writing Final Classes and Methods page from The Java Tutorials has more information.

like image 38
coobird Avatar answered Oct 04 '22 00:10

coobird