marscom
marscom

Reputation: 625

How can I use multiple objects in the same fashion?

I am looking for help with having multiple different types of system accessed within java as if they are the same.

For example, I have the classes

private class SystemA{

    public void in(boolean input){
      //do x;
    }
    public boolean out(){
      //return x;
    }
}

Say I want to have an ArrayList of different systems. These systems all implement the functions in and out like SystemA does, but they will be different objects all with different internal architectures.

I would like to for example iterate through the aformentioned arraylist, calling out() on all of the objects - how can I:

Store multiple different object types. Ensure that I can call the in and out functions on the object in the arraylist, not needing to worry that the object is one specific type or another.

Upvotes: 0

Views: 73

Answers (2)

Lukas Eder
Lukas Eder

Reputation: 220902

Let your system classes implement a new MySystem interface:

public interface MySystem {
    void in(boolean input);
    boolean out();
}

E.g.:

private class SystemA implements MySystem {
    @Override
    public void in(boolean input) { ... }
    @Override
    public boolean out() { ... }
}

Your ArrayList will then look like any of these:

List<MySystem> list = new ArrayList<MySystem>();
List<? extends MySystem> list = someFactoryMethod();

I suggest reading the Java tutorial "What Is an Interface?" for more details. Also, read up on "subtype polymorphism" in general.

Upvotes: 2

SomeWittyUsername
SomeWittyUsername

Reputation: 18358

That's a broad question. What you need is polymorphism. Read about Java polymorphism here: http://home.cogeco.ca/~ve3ll/jatutor5.htm

Upvotes: 0

Related Questions