javaobjectmethodsreturnsubclass

How do I call the method from a class that creates other objects?


I have five classes. My Main class, a form class, two subclasses that extend the form class and a createForm class I am forced to use to create new instances of the subclass.

public class FormenFabrik {
    public Form createForm(String newform) {
        if(newform.equals("Kreis")) {
            Form newKreis = new Kreis();
            return newKreis;
        }else{
            Form newRechteck = new Rechteck();
            return newRechteck;
        }
    }
}

We're forced to use public Form createForm(String string){} as our method. We're supposed to pass a String to the method and depending on what form we pass over ("Circle" or "Rectangle"), the method returns either a new Circle or a new Rectangle.

But I can't figure out how to call that method from my Main class.


Solution

  • This type of construction is called a "factory". The answer to your question as written is to first create a FormenFabrik object, then call that object's createForm method:

    FormenFabrik fabrik = new ForminFabrik();
    Form form = fabrik.createForm("Kreis");
    

    However, this is a nonstandard way of writing factory methods, and it forces you to create a FormenFabrik object that doesn't need to exist. Since you don't access any instance variables in createForm, you can make the class cleaner by making the method static instead:

    public class FormenFabrik {
        public static Form createForm(String newform) {
            if (newform.equals("Kreis")) {
                Form newKreis = new Kreis();
                return newKreis;
            } else {
                Form newRechteck = new Rechteck();
                return newRechteck;
            }
        }
    }
    

    Then, you can skip the instantiation step and call the factory method directly.

    Form form = FormenFabrik.createForm("Kreis");