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
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With