If I have an interface A and an interface B that extends A. In a List of A how can I recognise the objects that implement B and so call the methodB of interface B on them?
public interface A{
void methodA();
}
public interface B extends A{
void methodB();
}
public class CA implements A{
public void methodA(){}
}
public class CB implements B{
public void methodA(){}
public void methodB(){}
}
public static void main(String [] args){
List<A> l = new ArrayList<>();
l.add(new CA());
l.add(new CB());
}
Should I use instanceof or there are better solution using polymorphism?
Edit: I’am trying to develop a hierarchy to execute some commands for a simple game. The basic commands like Move and MoveRandom implements the interface Command. Now I want to add a repeat command and to manage the loop I have extended the Command interface with a LoopCommand interface(to respect the interface segregation principle). So when I have the List of Commands I need to know if the command is a LoopCommand and in this case call the anotherIteraction() method to know if stay on the command or go to the next command. For this reason I have done the initial question. There are better hierarchy or solution to manage the loop commands?
public interface Command{
void execute();
}
public interface LoopCommand extends Command{
public boolean anotherIteraction();
}
public class Move implements Command{
public void execute(){}
}
public class Repeat implements LoopCommand{
private List<Command> body;
private repetition;
boolean anotherIteraction(){
/*logics to determinate if there are other commands to execute*/
}
public void execute(){/*execute 1 command from the list body*/}
}
public static void main(String[] args){
List<Command> l = new ArrayList<>();
l.add(new Move());
l.add(new Repeat());
int i=0;
while(i<l.size()){
l.get(i).execute();
if(l.get(i) instance of LoopCommand c){
if(!c.anotherIteraction)
i++;
} else
i++;
}
}
You can do it using instanceof
import java.util.ArrayList;
import java.util.List;
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
class CA implements A {
public void methodA() {
System.out.println("CA's implementation of interface A");
}
}
class CB implements B {
public void methodA() {
System.out.println("CB's implementation of interface A");
}
public void methodB() {
System.out.println("CB's implementation of interface B");
}
}
public class InstanceOfDemo {
public static void main(String[] args) {
List<A> list = new ArrayList<>();
list.add(new CA());
list.add(new CB());
for (A obj : list) {
if (obj instanceof B ob) {
ob.methodB();
} else {
obj.methodA();
}
}
}
}
prints
CA's implementation of interface A
CB's implementation of interface B