Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Inheritance and Method Overriding in Object-Oriented Java

Tech 2

Inheritance establishes a parent-child relationship where a parent class encapsulates common attributes and behaviors, while child classes define their specific characteristics.

A child class uses the extends keyword to inherit all members from the parent class, except for constructors. Members marked as private in the parent class are not directly accessible in the child class; they must be accessed indirectly through public or protected methods provided by the parent.

Parent Class Definition

public class ParentAccount {
    int balance;
    String accountHolder;
    private int secretCode;
    static int sharedCounter;

    private void secureOperation() {
        System.out.println("Private method executed.");
    }

    public int retrieveSecret() {
        return secretCode;
    }

    public void updateSecret(int newCode) {
        this.secretCode = newCode;
    }

    public void invokeSecure() {
        secureOperation();
    }

    public void calculateRevenue() {
        System.out.println("Parent generates 300 units.");
    }
}

First Child Class

public class FirstChildAccount extends ParentAccount {
    String childIdentifier;

    @Override
    public void calculateRevenue() {
        System.out.println("First child generates 30 units.");
    }

    public void childSpecificAction() {
        System.out.println("Action unique to first child.");
    }
}

Second Child Class

public class SecondChildAccount extends ParentAccount {
    String childTag;

    @Override
    public void calculateRevenue() {
        System.out.println("Second child generates 3000 units.");
    }

    public void secondChildMethod() {
        System.out.println("Method specific to second child.");
    }
}

Demonsrtating Inheritance

public static void main(String[] args) {
    ParentAccount parent = new ParentAccount();

    FirstChildAccount childOne = new FirstChildAccount();
    String nameOne = childOne.accountHolder = "Primary Offspring";
    childOne.childSpecificAction(); // Output: Action unique to first child.
    System.out.println(nameOne); // Output: Primary Offspring

    SecondChildAccount childTwo = new SecondChildAccount();
    String nameTwo = childTwo.accountHolder = "Secondary Offspring";
    childTwo.secondChildMethod(); // Output: Method specific to second child.
    System.out.println(nameTwo); // Output: Secondary Offspring

    // Accessing private field via public setter/getter
    childTwo.updateSecret(4);
    int retrievedSecret = childTwo.retrieveSecret();
    System.out.println(retrievedSecret); // Output: 4

    // Accessing private method via a public wrapper
    childOne.invokeSecure(); // Output: Private method executed.

    // Accessing static member
    int counterValue = FirstChildAccount.sharedCounter = 3;
    System.out.println(counterValue); // Output: 3
}

Method Overriding

Method overriding allows a child class to provide a specific implementation for a method already defined in its parent class.

Testing Overridden Methods

public static void main(String[] args) {
    ParentAccount base = new ParentAccount();
    FirstChildAccount derivedOne = new FirstChildAccount();
    SecondChildAccount derivedTwo = new SecondChildAccount();

    base.calculateRevenue(); // Output: Parent generates 300 units.
    derivedTwo.calculateRevenue(); // Output: Second child generates 3000 units.
    derivedOne.calculateRevenue(); // Output: First child generates 30 units.
}

Using the super Keyword

The super keyword references the immediate parent class, similar to how this references the current object. It can be used to call parent class constructors, methods, or access fields (excluding private ones).

Enhanced Parent Class with Constructor

public class ParentAccount {
    int balance;
    String accountHolder;
    private int secretCode;
    static int sharedCounter;

    private void secureOperation() {
        System.out.println("Private method executed.");
    }

    public ParentAccount() {
        System.out.println("Parent class no-argument constructor.");
    }

    public int retrieveSecret() {
        return secretCode;
    }

    public int updateSecret(int newCode) {
        this.secretCode = newCode;
        return newCode;
    }

    public void invokeSecure() {
        secureOperation();
    }

    public void calculateRevenue() {
        System.out.println("Parent generates 300 units.");
    }
}

Child Class Utilizing super

public class FirstChildAccount extends ParentAccount {
    String childIdentifier;

    @Override
    public void calculateRevenue() {
        System.out.println("First child generates 30 units.");
    }

    public FirstChildAccount() {
        super(); // Must be the first statement in the constructor.
        super.updateSecret(3);
        int codeValue = super.retrieveSecret();
        System.out.println(codeValue); // Output: 3
    }

    public void childSpecificAction() {
        System.out.println("Action unique to first child.");
    }

    public static void main(String[] args) {
        new FirstChildAccount();
        // Output:
        // Parent class no-argument constructor.
        // 3
    }
}

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.