-2

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.

1
  • Should createForm() be a static method or non-static method? Commented Apr 5 at 22:54

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

Comments

2

You already have a class called FormenFabrik that creates either a Kreis or Rechteck depending on the string you give it. Now, to use that from your Main class, you just need to:

Make an object of FormenFabrik.

Call the method createForm("Kreis") or createForm("Rechteck") on that object.

It will give you back a Form object, which you can use.

Here’s what your Main class might look like:

public class Main {
    public static void main(String[] args) {
        FormenFabrik fabrik = new FormenFabrik();

        // Create a Kreis (Circle)
        Form form1 = fabrik.createForm("Kreis");
        form1.draw();  // Output: Drawing a circle. replace the method draw with whatever method Form has

        // Create a Rechteck (Rectangle)
        Form form2 = fabrik.createForm("Rechteck");
        form2.draw();  // Output: Drawing a rectangle.
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.