When a predefined method in Java is overridden...
- Only the method signature must be same
- Both method signature and inheritance must be same
What is the answer? 1 or 2
I know that when we override the method in superclass, the method signature should be the same. But what about the inheritance? I have read this question in a book, but I did not find any answer even after some research.
From the docs:
The method signature must be the same; that is, the name, parameters, position of parameters, and number of parameters must match.
The most common example of this is
toString()
, which lives onObject
.Object
'stoString
method is defined as this:...whereas
AbstractCollection
*'stoString
method is defined as this:Notice that both of the method signatures are the same, but what they return is different. This is the intention of overriding; your parent class has defined specific behavior for it that doesn't necessarily make sense in the children classes, so one simply overtakes that behavior and makes it suitable for the child class.
*: This is used for anything that is an
AbstractCollection
, likeArrayList
andLinkedList
.To expand a bit: the visibility of the method in the child also plays a role.
From this handy chart, methods that have the
private
modifier cannot be passed to subclasses.When overriding methods, you cannot reduce the visibility of a method; that is, you cannot descend lower in the visibility order provided.
To help, here's a quick list.
If the method in your parent is...
public
: the subclass' override must bepublic
.protected
: the subclass' override can either bepublic
orprotected
.<no modifier>
or package-private: the subclass' override can bepublic
,protected
, or package-private.private
: the subclass doesn't even know the method exists.