Method Overriding in Java — Java Technical Interview Questions & Answers

Method Overriding in Java

Method Overriding in Java

  • Overriding = child rewrites a parent method with the same signature: same name, same parameters. Put @Override so the compiler catches mistakes.
  • At runtime, a parent reference can call the child’s version: Animal a = new Dog(); a.sound();. Access cannot be tighter in the child. Purpose is specialised behaviour.
  • If you change parameters, it is not overriding — it becomes overloading or a new method. Show Animal/Dog sound() with a parent reference.
  • Let's take this on the board with one tiny Main class — no extra files. Method Overriding in Java — output: 25. square(5) returns 5*5. Change to square(6) → 36. Start from main, go line by line, and stop at each print. That output is the proof for Method Overriding.

Technical Interview Tip: Parent ref + child object demo for overriding.

Code Examples for Method Overriding in Java

Example

public class Main {
  static int square(int n) { return n * n; }
  public static void main(String[] args) {
    System.out.println(square(5));
  }
}

Method Overriding in Java — output: 25. square(5) returns 5*5. Change to square(6) → 36.

How to Explain Method Overriding in Java to an Interviewer

What is overriding?

Child rewrites parent method Same signature

Why @Override?

Compiler catches mistakes

When is overriding decided?

Runtime