Can all Java methods be overridden?
If not, what kind of method can't be overridden? Private methods? Constructor methods?
Please explain why.
Can all Java methods be overridden?
If not, what kind of method can't be overridden? Private methods? Constructor methods?
Please explain why.
Razib and Mick are correct about the types of function that cannot be overridden, but perhaps you would appreciate some extrapolation on why those different functions can't be overridden. I'll go through each type in turn.
private
method:
A method declared as private is intended to be hidden from all code outside the class where it is defined. This promotes encapsulation, or the ability to ensure that other bits of code are not relying on how you chose to implement your class. If you want a method to be accessible for override by classes which inherit from yours, use the protected
modified instead of private
(see the doc for access modifiers).Constructor: The constructor of a class is intended to create an instance of that class, and thus is not inherited by inheriting classes (see this related question). If you're looking to do something like constructor overriding, you can create a constructor in the inheriting class with the same signature as one from the parent class.
final
methods or methods from a final
class:
The final
keyword can be used specifically to ensure that no implementing class can override your method, or that no class can inherit from yours. This can be used for several purposes- including security or prevention of unintended consequences. See this related question.
static
methods:
The static
keyword can be applied to a method to indicate that the method belongs to the class itself, and not to a particular instance. Since these methods belong to the class and not a particular instance, you could never have a an object who has inherited the method. Thus the concept of overriding such a method has no meaning. See this related question.
A final
method cannot be overridden in Java. Also, methods declared private
or within a final class
behave as if they're final
.
Why? Because this is how it's specified in the JLS.
Here is some points:
1. Function marked as final
can not be overridden in child class.
2. private
function in parent class is not inherited to the child class. So overriding is not applicable for private method.
3. And constructor is not a function. Moreover constructor is not inherited to child class. So you can not override a constructor. But you can overload a constructor.