1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Inheritance
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
20Hrs
35Mins
03Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Inheritance

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
20Hrs
35Mins
03Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Inheritance

Overview

Inheritance is the OOP mechanism that allows a new class (the Child/Subclass) to absorb the attributes and methods of an existing class (the Parent/Superclass). It heavily promotes code reusability and establishes a hierarchical relationship.

For example, instead of writing separate Dog, Cat, and Bird classes that all duplicate the eat() and sleep() methods, you create a parent Animal class. The subclasses use the extends keyword to instantly inherit those behaviors, allowing them to focus entirely on their unique traits (like bark() for Dog, or fly() for Bird).

Java enforces Single Inheritance for classes. A child class can only extend exactly ONE parent class, preventing the notorious 'Diamond Problem' found in C++ where a child inherits conflicting methods from multiple parents.

Syntax

Extending a Parent Class
java
// The Parent Class (Superclass)
public class Animal {
    String name;
    
    public void eat() {
        System.out.println(name + " is eating.");
    }
}

// The Child Class (Subclass)
// 'extends' grants the Dog all of Animal's non-private members
public class Dog extends Animal {
    
    public void bark() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        
        myDog.name = "Rex"; // Inherited attribute!
        myDog.eat();        // Inherited method!
        myDog.bark();       // Unique child method!
    }
}

Common Pitfalls

  • Attempting Multiple Inheritance. Writing class Child extends Father, Mother will cause an instant compilation error. Java classes can only have one direct parent.
  • Assuming private fields are inherited. A child class does NOT inherit variables or methods marked as private in the parent class. If you want the child to access them but keep them hidden from the outside world, you must use the protected access modifier.

Interview Questions

Is it true that every single class in Java inherits from something?

Yes! If you do not explicitly use the extends keyword, Java implicitly injects extends Object. The java.lang.Object class is the ultimate root parent of every single class in Java, granting universal methods like .toString() and .equals().

What is an 'IS-A' relationship?

Inheritance establishes an 'IS-A' relationship. Because a Dog extends Animal, a Dog IS-A(n) Animal. This is a critical concept for Polymorphism, allowing you to store a Dog object inside an Animal reference variable.

Real-World Example

UI frameworks (like Android or JavaFX) rely heavily on Inheritance. They provide a generic View class that handles core logic like width, height, and margins. Developers then create specific elements like Button extends View and TextView extends View.

example
java
public class Button extends View {
    // Inherits setWidth(), setHeight(), and isVisible from View
    
    // Only handles Button specific logic
    public void setOnClickListener(Action a) { ... }
}

Check Your Knowledge

Test your understanding of Inheritance with these quick questions.

Question 1

Which keyword is used to establish an inheritance relationship between two classes?

Question 2

How many parent classes can a Java class extend simultaneously?

Question 3

Which access modifier allows a child class to inherit a member, while keeping it hidden from the rest of the world?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Inheritance

Overview

Inheritance is the OOP mechanism that allows a new class (the Child/Subclass) to absorb the attributes and methods of an existing class (the Parent/Superclass). It heavily promotes code reusability and establishes a hierarchical relationship.

For example, instead of writing separate Dog, Cat, and Bird classes that all duplicate the eat() and sleep() methods, you create a parent Animal class. The subclasses use the extends keyword to instantly inherit those behaviors, allowing them to focus entirely on their unique traits (like bark() for Dog, or fly() for Bird).

Java enforces Single Inheritance for classes. A child class can only extend exactly ONE parent class, preventing the notorious 'Diamond Problem' found in C++ where a child inherits conflicting methods from multiple parents.

Syntax

Extending a Parent Class
java
// The Parent Class (Superclass)
public class Animal {
    String name;
    
    public void eat() {
        System.out.println(name + " is eating.");
    }
}

// The Child Class (Subclass)
// 'extends' grants the Dog all of Animal's non-private members
public class Dog extends Animal {
    
    public void bark() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        
        myDog.name = "Rex"; // Inherited attribute!
        myDog.eat();        // Inherited method!
        myDog.bark();       // Unique child method!
    }
}

Common Pitfalls

  • Attempting Multiple Inheritance. Writing class Child extends Father, Mother will cause an instant compilation error. Java classes can only have one direct parent.
  • Assuming private fields are inherited. A child class does NOT inherit variables or methods marked as private in the parent class. If you want the child to access them but keep them hidden from the outside world, you must use the protected access modifier.

Interview Questions

Is it true that every single class in Java inherits from something?

Yes! If you do not explicitly use the extends keyword, Java implicitly injects extends Object. The java.lang.Object class is the ultimate root parent of every single class in Java, granting universal methods like .toString() and .equals().

What is an 'IS-A' relationship?

Inheritance establishes an 'IS-A' relationship. Because a Dog extends Animal, a Dog IS-A(n) Animal. This is a critical concept for Polymorphism, allowing you to store a Dog object inside an Animal reference variable.

Real-World Example

UI frameworks (like Android or JavaFX) rely heavily on Inheritance. They provide a generic View class that handles core logic like width, height, and margins. Developers then create specific elements like Button extends View and TextView extends View.

example
java
public class Button extends View {
    // Inherits setWidth(), setHeight(), and isVisible from View
    
    // Only handles Button specific logic
    public void setOnClickListener(Action a) { ... }
}

Check Your Knowledge

Test your understanding of Inheritance with these quick questions.

Question 1

Which keyword is used to establish an inheritance relationship between two classes?

Question 2

How many parent classes can a Java class extend simultaneously?

Question 3

Which access modifier allows a child class to inherit a member, while keeping it hidden from the rest of the world?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A