This question may be simple (I wish it is not) but i found in an interview. In general, given an interface class IntClass, and a number of classes that implements the interface named ImpIC1, ImpIC2, ..., ImpICk. The methods in IntClass are abstract public methods named void action1(), void action2() ..., void actionM().
I was given a public class Test with public static function named: public static IntClass foo(IntClass c1, IntClass c2). This method do some operations on c1 and c2 to create an an InClass and returns. However, the method must work for every valid implementation of IntClass. The problem is mainly with the definition of c3. How would I design method foo() ..
see below for code details:
public interface IntClass {
abstract void action1();
..
abstract void actionM();
}
..
public class ImpIC1 implements IntClass {
public void action1() { ... }
public void action2() { ....}
..
public void actionM() { ... }
}
...
public class ImpIC2 implements IntClass {
public void action1() { ... }
public void action2() { ....}
..
public void actionM() { ... }
}
...
public class ImpICk implements IntClass {
public void action1() { ... }
public void action2() { ....}
..
public void actionM() { ... }
}
...
public class Test {
public static IntClass foo(IntClass c1, IntClass c2) {
....
...
return c3;
}
}
...
The problem is mainly with the definition of c3. I tried the following solutions (none of which work):
- inside foo, c3 was defined as instance of Object .. i.e. IntClass c3 = (IntClass) new Object(). -- compile-time error Object cannot be cast to IntClass
- inside foo, c3 was left with no initializion. (compile time error).
- inside foo, c3 is null, (null pointer exception)
- inside foo, c3 is initialized as one of the implemtation of c3 (i.e. c3 = (IntClass) new ImpIC1()) .. the problem is that if we execute in the exterior ImpIC2 s = (ImpIC1) foo(c1,c2) - we get an error (unable to cast).
c3
supposed to be? How does it relate toc1
andc2
? – cheekenc3
to be anIntClass
. But what is insidec3
? How are you combiningc1
andc2
to make it? If you simply want to return anyIntClass
at all, why not doreturn ImplC1()
? – cheekenreturn null;
would not satisfy this problem. – emory