Lets say I have two similar class:
public class First {
public static final String ONE = "1";
public static final String TWO = "2";
public static final String THREE = "3";
}
public class Second {
public static final String ONE = "one";
public static final String TWO = "two";
public static final String THREE = "three";
}
Now in other class Im using one of them:
public class Third {
//....
@Override
public String toString()
{
System.out.println( First.ONE );
}
}
But what I’m trying to do now, is make kind of selector, lets say constructor of class Third gets boolean value and based on it select which class use, but I dont want to make if (..) statement everywhere, cause its simply too much.
So in abstract I’d like this:
public class Third {
//some global var with reference? to static class
public Third(boolean first)
{
if( first ) {
//set class First as source of static fields
} else {
//set class Second
}
}
//....
@Override
public String toString()
{
System.out.println( globalVariableWithReference.ONE );
}
}
Is it possible without making an istance of these class?
You could use an interface with getter methods, then have the two classes implement that interface (and return their respective values when the getter methods are called). Then you can create a map to map between the boolean value and the two implementation classes (via the interface), and call the object that maps to the boolean. Of course, this requires that you create an object of each class, but you would get the same behavior.
Another option is to create a wrapper class that wraps the
if/elselogic into its own static methods and return the appropriate value from the two classes based on the boolean value. While you will need to write theif/elselogic for this wrapper clasee, you do not need to write it more than once, just call the wrapper class’s methods