How to create a common class that can act as either of two class depending on need.
I tried using
But I didn't get result as expected,
public class classA{
int value = 1;
}
public class classB{
int value = 2;
}
public class classC{
Object commonClass;
classC(classA a){
commonClass = a;
}
classB(classB b){
commonClass = b;
}
int getValue(){
return commonClass.value;
}
}
public static void main(String args[])
{
classC c1 = new classC(new classA);
classC c2 = new classC(new classB);
System.out.println(c1.getValue());
System.out.println(c2.getValue());
}
/*
output must be
c1.getValue() => 1
c2.getValue() => 2
*/
@LouisWasserman 's point is a good one. You'd probably be better off creating a common superclass. But in terms of your existing code:
public class classC{
Object commonClass;
classC(classA a){
commonClass = a;
}
//This constructor is wrong. It needs to be classC(classB b)
classB(classB b){
commonClass = b;
}
int getValue(){
//You need a cast here
// return commonClass.value;
if (commonClass instanceof classA) {
return ((classA) commonClass).value;
} else {
return ((classB) commonClass).value;
}
}
}
public static void main(String args[])
{
//you need parentheses for creating your objects
// classC c1 = new classC(new classA);
// classC c2 = new classC(new classB);
classC c1 = new classC(new classA());
classC c2 = new classC(new classB());
}