Home > front end >  How to create a classC that act as either classA or classB
How to create a classC that act as either classA or classB

Time:10-28

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

CodePudding user response:

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

CodePudding user response:

These two lines suggest your attempt to use inheritance was backwards:

  • "How to create a classC that act as either classA or classB" (Question title)
  • "class classC extends classA, classB" (from list of attempts)

classC should be your base class. classA and classB should extend classC.

public class ClassC {
    private int value;
    public ClassC () { value = 0; }
    public ClassC (int v) { value = v; }    

    public int getValue () { return value; }    
}


public class ClassA extends ClassC {
    public ClassA () { super (1); }
}

public class ClassB extends ClassC {
    public ClassB () { super(2); }    
    
    @Override
    public int getValue () { return - (super.getValue() * super.getValue()); }
}



public class Example {
    public static void main (String [] args) { 
        ClassC c1 = new ClassA ();
        ClassB c2 = new ClassB ();
        
        System.out.println ("C1: "   c1.getValue());
        System.out.println ("C2: "   c2.getValue());
    }
}

Output:

C1: 1
C2: -4
  • Related