Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Inheritance and Object-Oriented Principles

Tech May 10 3

Defining Subclasses

In Java, inheritance is established using the extends keyword. A derived class (subclass) inherits fields and behaviors from its base class (superclass) and can introduce new functionalities.

public class Supervisor extends Worker
{
    // extended behaviors and state
}

Method Overriding and the Super Keyword

When a subclass needs to alter the implementation of an inherited method, it employs method overriding. The @Override annotation explicitly marks such methods. Inside an overridden method, the super keyword is essential to invoke the parent class's version of the method, preventing infinite recursion.

class Worker {
    private String identifier;
    private double baseWage;

    public Worker(String identifier, double baseWage) {
        this.identifier = identifier;
        this.baseWage = baseWage;
    }

    public double calculatePay() {
        return baseWage;
    }
}

class Supervisor extends Worker {
    private double performanceBonus;

    public Supervisor(String identifier, double baseWage) {
        super(identifier, baseWage);
    }

    public void setPerformanceBonus(double bonus) {
        this.performanceBonus = bonus;
    }

    @Override
    public double calculatePay() {
        return super.calculatePay() + performanceBonus;
    }
}

The super keyword serves multiple purposes within a subclass:

  • Constructor Chaining: Invoking super() executes the parent's initialization logic. Absence of an explicit call defaults to the no-argument constructor.
  • Method Invocation: Calling super.methodName() accesses the parent's implementation of an overridden method.
  • Field Access: It allows direct access to parent class members shadowed by subclass fields.

Conversely, the this keyword references the current object instance:

  • Instance Variable Resolution: Differentiating between local parameters and instance fields (e.g., this.identifier = identifier).
  • Internal Method Calls: Triggering another method within the same object context.
  • Instance Return: Returning the current object reference to enable method chaining.
public class Builder {
    private int threshold;

    public Builder setThreshold(int threshold) {
        this.threshold = threshold;
        return this; // enables chaining
    }
}

SOLID Design Principles

Object-oriented architecture heavily relies on the five SOLID guidelines:

  1. Single Responsibility Principle (SRP): A class should encapsulate a single cohesive functionality, ensuring only one factor drives its modifications.
  2. Open-Closed Principle (OCP): Software components must be open for behavioral extension but closed for structural modification.
  3. Liskov Substitution Principle (LSP): Derived types must seamlessly substitute their base types without altering the program's correctness.
  4. Interface Segregation Principle (ISP): Clients should not be forced to depend on interface methods they do not utilize.
  5. Dependency Inversion Principle (DIP): High-level policies and low-level details should both rely on shared abstractions, not on each other directly.

Polymorphism

Polymorphism enables a single interface to represent different underlying behaviors. Method overloading (compile-time) and method overriding (runtime) are its two primary mechanisms in Java.

abstract class Notification {
    public abstract void dispatch();
}

class EmailAlert extends Notification {
    @Override
    public void dispatch() {
        System.out.println("Sending email notification...");
    }
}

class PushAlert extends Notification {
    @Override
    public void dispatch() {
        System.out.println("Triggering push notification...");
    }
}

Restricting Inheritance with Final

Applying the final modifier to a class declaration blocks any further subclassing. Similarly, a final method cannot be overridden by descendants, locking its implementation.

public final class ImmutableSupervisor extends Worker {
    // cannot be extended
}

public class Worker {
    private String identifier;

    public final String getIdentifier() {
        return identifier; // cannot be overridden
    }
}

Abstract Classes

An abstract class establishes a partially defined template. It cannot be instantiated directly. Abstract methods within it lack a body and mandate concrete implementation in extending subclasses.

public abstract class Device {
    public abstract String getHardwareInfo();
}

Access Control Modifiers

Java enforces four distinct visibility scopes:

  • private: Visible solely within the declaring class.
  • public: Accessible from any external context.
  • protected: Available to classes within the identical package and all subclasses regardless of package.
  • Default (Package-Private): Visible exclusively to classes sharing the same package, lacking an explicit modifier.

Wrapper Classes and Autoboxing

Primitive types map to corresponding reference types via wrapper classes: Integer, Long, Float, Double, Short, Byte, Character, and Boolean. Autoboxing seamlessly transitions primitives to their wrapper counterparts, while unboxing reverses the process, handled implicitly by the compiler.

Variable Arguments (Varargs)

Methods accepting an undetermined number of parameters utilize variable arguments, denoted by three dots (...). This syntax transforms the supplied arguments into an array internally.

public static int findMinimum(int... inputs) {
    int lowest = Integer.MAX_VALUE;
    for (int current : inputs) {
        if (current < lowest) {
            lowest = current;
        }
    }
    return lowest;
}

public static void main(String[] args) {
    int result = findMinimum(42, 7, 19, 3, 88);
    System.out.println(result); // outputs 3
}

Enumeration Types

Enumerations define a fixed set of named constants using the enum keyword. They implicitly extend java.lang.Enum and differ from standard classes by enforcing constant declarations at the onset, separated by commas.

public enum Season {
    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}

Related Articles

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...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

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