1

I'm slightly new to programming, and I am stuck. Say I have five different classes in a project: foo1, foo2, foo3, foo4, and foo5 that all do different, but similar things. Now say I need to create a new object of each one, so something like: foo1 bar1 = new foo1(); foo2 bar2 = new foo2(); foo3 bar3 = new foo3(); and so on. Sure that works, but I'm really trying to find a way to conserve a lot of space if I could instantiate all the objects I need in a single for-loop, or in the least put all the objects I want to create in a single Array to work out of. I can get it working if it was all the same Class, but not if it would be different. Is it even possible?

1
  • You should read about what is polymorphism. Commented Nov 13, 2016 at 2:16

3 Answers 3

0

Try to read something about polymorphism which you can use in Java. How does the Interfaces and Abstract classes works. What is extends and implements keyword in Java and other ...

I found these tutorials which looks good:

TutorialsPoint polymorphism

Oracle polymorphism

Sign up to request clarification or add additional context in comments.

Comments

0

If the class name is in sequence, then you can use below:

For(int i = 0; i < 10; i++) {
    try {
        Class<?> cls = Class.forName("foo"+i);
        arr[i] = cls.newInstance();
    } catch (ClassNotFoundException e) {
        System.out.println("Class not found " + e);
    }
}

But since all the objects are heterogeneous, the array will have to be of type Object[]

Comments

0

Sounds like the factory method pattern is what you are looking for.

The task you are attempting to handle polymorphically is a bit different than the usual, since instantiation usually requires you to know the concrete type of the object you want to create. Factories will allow you to do this.


First, you need to ensure the types you want to instantiate derive from the same interface:

interface Foo { }
class Foo1 implements Foo { }
class Foo2 implements Foo { }

You can then define a factory type:

interface FooFactory {
    Foo createFoo();
}

Create implementations of FooFactory that return different types of Foo:

class Foo1Factory implements FooFactory {
    public Foo createFoo() {
        return new Foo1();
    }
}

class Foo2Factory implements FooFactory {
    public Foo createFoo() {
        return new Foo2();
    }
}

Store these factories in an array:

FooFactory[] factories = {
    new Foo1Factory(),
    new Foo2Factory()
}

Then loop through the array, calling createFoo() on each factory:

for(FooFactory factory : factories) {
    Foo foo = factory.createFoo();
    //...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.