BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Common Errors in Inheritance in Java: Examples and solutions

Last Updated: December 14, 2024 by Chaitanya Singh | Filed Under: java

In previous tutorials, we discussed inheritance in java and types of inheritance in Java. In this guide, we will discuss some of the common errors in inheritance in java along with examples and solutions.

1. Using private Members in Subclasses

Error: A subclass cannot access private members of its parent class directly. In the following example, the Child class tries to access the private variable of Parent class which resulted in an error.

class Parent {
private int num = 101;
}
class Child extends Parent {
void display() {
System.out.println(num); // Error: num has private access in Parent
}
}

Solution: To avoid this error, you can use two solutions:

  1. Use protected or public access modifiers for variable num, this would ensure that the variable is accessible in other classes. The protected variables are only accessible to child classes while public variables are accessible to all classes. I have discussed this here: Access modifiers in Java.
  2. If you wish to keep the private access modifier then you can provide getter and setter method in the Parent class to access the variable in child classes.

2. Misunderstanding super Keyword

Error: Using super incorrectly to call parent class constructors or methods.

class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super(); // Optional, but must be the first statement in the constructor
System.out.println("Child Constructor");
}
}

Solution: Ensure super() is the first statement in the subclass constructor if used. I have covered this here: Super keyword in Java.

3. Failing to Override Correctly

Error: Forgetting to use the @Override annotation or mismatching method signatures. I have covered the Override annotation here: Java Override annotation.

class Parent {
void display() {
System.out.println("Parent");
}
}
class Child extends Parent {
@Override
void display() { // Without `@Override`, errors may go unnoticed
System.out.println("Child");
}
}

Solution: Always use @Override to catch signature mismatches during compilation.


4. Circular Inheritance

Error: A class cannot extend itself or create a circular dependency. This is pretty self explanatory, you should avoid such errors while writing code.

class A extends A {} // Error: cyclic inheritance not allowed

Solution: Redesign the hierarchy to avoid circular dependencies.


5. Constructor Confusion

Error: Forgetting that parent class constructors are not inherited.

class Parent {
Parent(int value) {
System.out.println("Parent: " + value);
}
}
class Child extends Parent {
// Error: Parent class does not have a default constructor
}

Solution: Explicitly call the appropriate parent constructor using super(value).


6. Overriding Static Methods

Error: Static methods are not truly overridden; they are hidden. Read more here: static in java.

class Parent {
static void display() {
System.out.println("Parent");
}
}
class Child extends Parent {
static void display() {
System.out.println("Child");
}
}
Parent obj = new Child();
obj.display(); // Outputs "Parent"

Solution: Avoid relying on polymorphism for static methods.


7. Type Casting Errors

Error: Incorrectly casting objects between parent and child types.

Parent p = new Parent();
Child c = (Child) p; // ClassCastException

Solution: Use instanceof to check the object’s type before casting.


8. Infinite Recursion in Overriding

Error: Calling the same method itself. This would create infinite loop.

class Parent {
void display() {
display(); // Infinite recursion
}
}

Solution: Avoid doing this.


9. Multiple Inheritance via Classes

Error: Java does not support multiple inheritance with classes. I have discussed this here: Multiple inheritance in Java.

class A {}
class B {}
class C extends A, B {} // Error: Multiple inheritance not allowed

Solution: You can use interfaces where you need to use this feature.


10. Failing to Understand the final Keyword

Error: A final class cannot be inherited. If you try to inherit the final class, you will get an error. I have discussed this in detail: final in Java.

final class Parent {}
class Child extends Parent {} // Error: Parent is final

Solution: Make sure to avoid using final keyword for the classes and methods which you need in other classes.

Top Related Articles:

  1. Multithreading in java with examples
  2. StringJoiner toString() Method in Java
  3. Final Keyword In Java – Final variable, Method and Class
  4. Java – Static Class, Block, Methods and Variables
  5. Constructor Overloading in Java with examples

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap