Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to one subclass

Tags:

java

I'm a non-programmer with a very minimal coding exposure, but I'd like to modify an existing code base. I've greatly simplified the code I'm working with below. Please let me know if I can provide any further information or if this makes no sense at all! Vocab is hard. :)

In ClassA, I'm instantiating a subclass of ClassB. The change I'd like to make requires that a new variable, "myVar" (set in ClassA), is available to subclass ClassC but not subclass ClassD. What would be the most appropriate way to make that variable available to ClassC?

ClassA:

public class ClassA {
    private String myVar = "hi";
    private String myStuff = "bye";
    private int myOption = 1;

    private String getMyClass(String myStuff) throws Exception {
        final MyClassChoice myClass = getMyClassChoice(myOption);
        return myClass.getResponse(myStuff);
    }

    private MyClassChoice getMyClassChoice(myOption) {
        switch(myOption) {
            case 1:
                return new ClassC();
            case 2:
                return new ClassD();    
        }
    }
}

ClassB:

public class ClassB {
    public abstract String getResponse(String myStuff) throws IOException;
}

ClassC:

public class ClassC extends ClassB {
    // do stuff with myStuff
    // do stuff with myVar
}

ClassD:

public class ClassD extends ClassB {
    // do stuff with myStuff
}
like image 907
Jerm Avatar asked Sep 18 '26 20:09

Jerm


1 Answers

You either pass it to the constructor when instantiating the object and save it in an instance variable,

public class ClassA {
// ...
    private MyClassChoice getMyClassChoice(myOption) {
        switch(myOption) {
            case 1:
                return new ClassC(myVar);
            case 2:
                return new ClassD();    
        }
    }
}

public final class ClassC extends ClassB {

    private String myVar;

    // constructor:
    public ClassC(String myVar) {
        this.myVar = myVar;
    }

    // do stuff with myStuff
    // do stuff with myVar
    private void doStuff() {
        System.out.println(myVar);
    }
}

Or you pass it to the method when you use it,

public final class ClassA {
// ...
    public void someMethodUsingClassCDoStuff() {
        myClass.doStuff(myVar);
    }
}

public final class ClassC extends ClassB {

    // do stuff with myStuff
    // do stuff with myVar
    public void doStuff(String myVar) {
        System.out.println(myVar);
    }
}
like image 96
Arjan Avatar answered Sep 20 '26 09:09

Arjan