Sobes.tech
Junior

When is a method considered overridden?

sobes.tech AI

Answer from AI

A method is considered overridden when a method with the same signature (method name, number and types of parameters in the same order) is declared in a subclass as compared to a method in the parent class. Specifically:

  1. The method in the parent class must not be declared as final (or an equivalent modifier in other languages), which prohibits overriding.
  2. The access level of the overridden method in the subclass cannot be more restrictive than that in the parent class.
  3. The overridden method can return the same type as the method in the parent class, or a covariant type (a subtype of the original type).
  4. The overridden method cannot throw exceptions that are more general (or incompatible) than those declared in the parent method.
  5. Static methods cannot be overridden, only hidden.

When calling an overridden method through a reference to the parent class, but with an object of the subclass, the version of the method from the subclass is executed (polymorphism).

// Example in Java

class Parent {
    public void display() { // Method in parent class
        System.out.println("Parent display");
    }

    // final void cannotOverride() { ... } // This method cannot be overridden
}

class Child extends Parent {
    @Override // The @Override annotation helps the compiler verify that the method is indeed overridden
    public void display() { // Overridden method - same signature
        System.out.println("Child display");
    }
}
When is a method considered overridden? — QA / QA… - sobes.tech