Search code examples
javaclassobject

How to create a classC that act as either classA or classB


How to create a common class that can act as either of two class depending on need.

I tried using

  1. Object
  2. ArrayList list
  3. class classC extends classA, classB

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
*/

Solution

  • @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());
    }