Classes A, B, and C all implement InterfaceName, and also include their own specific methods not defined in the interface.
I have code that looks like this:
InterfaceName obj = null;
// initial type, can change
String type = "A"
Switch (type) {
case "A":
obj = ClassA();
break;
case "B":
obj = ClassB();
break;
case "C":
obj = ClassC();
break;
Now, based on this block, I assumed obj would be instantiated as one of the three, as there is no other option. I now have another switch block that tries to call specific methods. In this example, say ClassA has a method callMe, classB has a method writeMe, and classC has a method speakMe. But neither of these is defined in the interface InterfaceName. My next code block looks like this:
Switch (type) {
case "A":
obj.callMe();
break;
case "B":
obj.writeMe();;
break;
case "C":
obj.speakMe();
break;
My IDE, intelliJ, highlights all those methods in red, and java gives me an error "cannot find symbol" after compiling.
I've tried using if-else blocks instead, but nothing works. It looks like java is only allowing obj to call methods in the interface, and not in any of the classses implementing it. My guess would be because it was declared as InterfaceName, but still, shouldn't my switch blocks have some effect?
I have also tried to call the methods in the same switch block, right after instantiating it. I received the same error.
You need to cast your obj variable using the actual class that contains the method.
((ActualClass) obj).writeMe();