Inheritance in Java — Java Technical Interview Questions & Answers

Inheritance in Java

Inheritance in Java

  • Inheritance lets a child reuse and extend a parent. Keyword: class Dog extends Animal. IS-A idea: Dog is an Animal, so Dog can use parent features.
  • Java allows one parent class only (single class inheritance). Write common code once in the parent. Special code goes in the child. The child can add new methods and override parent methods.
  • Deep inheritance trees become hard to change. Keep them shallow. Extra capabilities come from interfaces: one superclass + many interfaces.
  • Let's take this on the board with one tiny Main class — no extra files. Inheritance in Java — output: Eating then Bark. Dog did not rewrite eat — it inherited it from Animal. Start from main, go line by line, and stop at each print. That output is the proof for Inheritance.
      Animal
      sound()
        │ extends
        ▼
       Dog
      sound()  →  bark

Technical Interview Tip: IS-A + single class inheritance + interfaces for extra contracts.

Code Examples for Inheritance in Java

Example

class Animal {
  void eat() { System.out.println("Eating"); }
}
class Dog extends Animal {
  void bark() { System.out.println("Bark"); }
}
public class Main {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.eat();
    d.bark();
  }
}

Inheritance in Java — output: Eating then Bark. Dog did not rewrite eat — it inherited it from Animal.

How to Explain Inheritance in Java to an Interviewer

What keyword is used for inheritance?

extends

How many parent classes can a Java class have?

One

What does IS-A mean?

Dog is an Animal Child is a type of parent