What happens when a method is overridden in Java?

167 Views Asked by At

When a predefined method in Java is overridden...

  1. Only the method signature must be same
  2. 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.

1

There are 1 best solutions below

2
On BEST ANSWER

From the docs:

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

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 on Object. Object's toString method is defined as this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

...whereas AbstractCollection*'s toString method is defined as this:

public String toString() {
    Iterator<E> it = iterator();
    if (! it.hasNext())
        return "[]";

    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {
        E e = it.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! it.hasNext())
            return sb.append(']').toString();
        sb.append(',').append(' ');
    }
}

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, like ArrayList and LinkedList.


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 be public.
  • protected: the subclass' override can either be public or protected.
  • <no modifier> or package-private: the subclass' override can be public, protected, or package-private.
  • private: the subclass doesn't even know the method exists.