Search code examples
javainheritancesubclasssuperclass

Inheritance involving subclass instances within superclass


I have an object A which after instantiating, I do various operations to its state. Within the methods of A, I need to create multiple instances (call them B) of another class. The class of objects B rely heavily on much of the state of A, and the instances can influence A's state.

The problem is as follows. Since A is already instantiated and operations are done on its state before the methods within A are invoked that require any instantiating of B, how can I use inheritance to write B's class, given that I do not want to call super() within B (as A is already instantiated)?

Do I have to combine B's class with A's class here?

public class Test {
    public static void main(String[] args) {
        ClassA instanceA = new ClassA(5000000L); //Initial instantiation and state-setting operation to A.
        instanceA.update(); //Try to get A to create B, where B relies on A's new state from previous operations.
    }   
}

class ClassA {
    long tempLong;
    ClassB instanceB;

    public ClassA(long setLong) {
        tempLong = setLong;
    }

    public void update() {
        this.instanceB = new ClassB(); //instanceA needs an instanceB to work with. 
    }

}

class ClassB extends ClassA {
    long tempLong2;

    public ClassB() {
        // I don't want to call super() here because instanceA is already created and instanceA's state is already set!;
        this.tempLong2 = super.tempLong*2; //instaceA's state is necessary for instanceB to function!
    }
}

Solution

  • There's a fundamental flaw in your design. You seem to believe that when you call update()

    public void update() {
        this.instanceB = new ClassB(); //instanceA needs an instanceB to work with. 
    }
    

    the new ClassB instance is related to this ClassA instance just because ClassB extends ClassA. NO, that isn't the case because new ClassB() creates an entirely new Object with a different ClassA state than this.

    If the only property that ClassB depends on ClassA for is temprature you're better off passing it through the constructor and scrapping inheritance here (if ClassB IS-NOT-A ClassA).

    public void update() {
        this.instanceB = new ClassB(this.tempLong);
    }
    
    public ClassB(long tempLong) {
        this.tempLong2 = tempLong * 2;
    }
    

    If the dependency requires access to almost all of ClassA properties, it may make more sense to favour HAS-A over inheritance here by passing ClassA instance to ClassB.

    public void update() {
        this.instanceB = new ClassB(this); // ClassA passes itself
    }
    
    public ClassB(ClassA classA) {
        this.classA = classA; // ClassB HAS-A ClassA relationship
        this.tempLong2 = classA.getTempLong() * 2;
    }