Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Inheritance in Java

Tech Nov 10 15

Definition of Inheritance

In Java, inheritance is a fundamental OOP concept that allows a new class (called a subclass or derived class) to be defined based on an existing class (called a superclass or base class). This mechanism enables subclasses to acquire the fields and methods of their parent class, promoting code reuse and eliminating redundant code implementations.

Subclasses inherit all members from their parent class, including fields and methods, unless those members are declared as private in the parent class. Private members remain inaccessible to subclasses due to encapsulation constraints.

The basic syntax for implementing inheritance is:

class SuperClass {
    // Superclass fields and methods
}

class SubClass extends SuperClass {
    // Subclass can define additional fields and methods
    // Subclass can override inherited methods
}

The extends keyword establishes the inheritance relationship between the two classes.

Key Characteristics

  1. Code Reusability: Subclasses inherit existing fields and methods from parent classes, eliminating the need to rewrite identical code.
  2. Extensibility: Subclasses can introduce new fields and methods or override parent class methods to provide specialized behavior.
  3. Polymorphism: Inheritance serves as the foundation for polymorphism. A subclass reference can be assigned to a parent class variable, enabling dynamic method binding.

Access Modifiers and Inheritance

Modifier Accessibility
public Accessible to all classes
protected Accessible to subclasses and classes in the same package
default (package-private) Accessible only to classes in the same package
private Not accessible to subclasses

Constructors

Subclasses do not inherit constructors from their parent class. When a subclass constructor doesn't explicitly invoke a parent constructor, Java automatically calls the parent's no-argument constructor. If the parent class lacks a no-argument constructor and the subclass doesn't explicitly call another constructor, a compilation error occurs.

The super keyword invokes the parent class constructor and must appear as the first statement in the subclass constructor.

Inheritance Limitations

Java does not support multiple inheritance (a class cannot extend more than one class). How ever, Java supports multilevel inheritance (a class can extend another class, which can further extend another class). To achieve multiple inheritance-like behavior, a class can implement multiple interfaces.

Advantages and Disadvantages of Inheritance

Advantages

  1. Code Reusability: Inherited fields and methods reduce code duplication across classes.
  2. Extensibility: Subclasses can extend parent functionality without modifying existing code.
  3. Type Hierarchy: Inheritance creates a clear class hierarchy that organizes related classes.
  4. Template Method Pattern: Parent classes can define algorithm frameworks while allowing subclasses to implement specific steps.

Disadvantages

  1. Tight Coupling: Subclasses become tightly coupled to parent classes, reducing flexibility.
  2. Encapsulation Violation: Subclasses can access protected and package-private members, potentially breaking encapsulation.
  3. Deep Hierarchy: Excessive inheritance depth complicates code maintenance and understanding.
  4. Reduced Flexibility: Composition (has-a relationship) often provides better flexibility than inheritance (is-a relationship) in many scenarios.

The Object Class

Overview

The Object class resides in the java.lang package, which is automatically imported for all Java programs. Every class in Java implicitly extends Object unlesss it explicitly extends another class, making Object the root of the Java class hierarchy.

Key Methods in Object Class

  1. Memory Management

    • finalize(): Called before garbage collection. Deprecated since Java 9 due to unpredictable behavior.
  2. Object Comparison

    • equals(Object obj): Compares object equality. Default implementation compares memory addresses.
    • hashCode(): Returns a hash code value based on memory address, used in hash-based collections.
  3. Object Cloning

    • clone(): Creates a copy of the object. Requires implementing Cloneable interface. Performs shallow copy by default.
  4. String Representation

    • toString(): Returns a string representation. Default returns class name and hash code.
  5. Class Information

    • getClass(): Returns the runtime class object, essential for reflection operations.

Method Overriding

Rules for Method Overriding

When overriding a method in a subclass, the following rules must be followed:

  1. Same Method Name: The overridden method must have identical name to the parent method.
  2. Same Parameter List: Parameter types, order, and count must match exactly.
  3. Return Type: Return type must be the same or a covariant type (Java 5+).
  4. Access Level: Cannot reduce accessibility. If parent method is public, override must be public.
  5. Exception Handling: Cannot declare new checked exceptions not declared in parent.
  6. Static Methods: Cannot override static methods—they are hidden, not overridden.
  7. Final and Private Methods: Cannot override final or private methods.

Overriding vs Overloading

Aspect Overriding Overloading
Location Between parent and child classes Within the same class
Method Name Same Same
Parameter List Must be identical Must differ
Return Type Same or covariant Can differ
Access Level Cannot be more restrictive No restriction
Polymism Type Runtime polymorphism Compile-time polymorphism

The super Keyword

The super keyword provides access to parent class members from within a subclass.

Accessing Parent Members

class Parent {
    int value = 100;
    void show() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
    int value = 200;
    
    void show() {
        System.out.println("Child method");
        System.out.println("Child value: " + value);
        System.out.println("Parent value: " + super.value);
        super.show();
    }
}

Calling Parent Constructors

class Child extends Parent {
    Child(int x) {
        super(x); // Calls parent constructor with parameter
    }
}

Important Notes

  • super can only be used within subclass contexts.
  • super() or super(arguments) must be the first statement in the constructor.
  • If no explicit super() call exists, Java implicitly calls the parent's no-argument constructor.

The final Keyword

final with Variables

  • Declares constants that cannot be reassigned
  • Must be initialized at declaration or in constructor
  • Convention: Use uppercase names for constant identifiers

final with Methods

  • Prevents method overriding in subclasses
  • Ensures method behavior remains consistent across inheritance hierarchy

final with Classes

  • Prevents class inheritance
  • Example: String is a final class in Java

Security Considerations

While final enhances code stability, it is not foolproof. Reflection APIs can potentially bypass final restrictions in certain scenarios.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.