fbid fbid - 5 years ago 226
Java Question

Decide what constructor call based on user input

I would need to ask the user how many sides has the Figure he wants to draw, then call the right constructor to instantiate the object.

Below is my attempt to solve the answer using IF statements (or I could have used a switch) , but I don't know if it's the best way to do this, possibly with Java inheritance and polymorphism.

All the classes extends the class Figure.


--------------- Figure ---------------
^ ^ ^ ^
| | | |
| | | |
Circle Triangle Rectangle Exagone


import java.util.Scanner;

class Draw {

static void main(String[] args){

Scanner userInput = new Scanner(System.in);
int num_sides;

//user input
System.out.println("How many sides has the figure you want to draw?");
num_sides = userInput.nextInt();

//---> deciding what constructor to call with if statements

if(num_sides == 0){
Figure f1 = new Circle();
else if(num_sides == 3){
Figure f1 = new Triangle();
System.out.println("Error. Invalid sides number");



class Figure{

private int sides;

public Figure(int num_sides){
sides = num_sides;

class Circle extends Figure{

public Circle(){


//... all the other classes has the same structure of Circle

Answer Source

Factory Methods

Have you considered the Factory Method Pattern? Basically, you have a method that's something like this:

public Figure createInstance(int numSides) {
    Figure figure = null;

    switch(numSides) {
    case 0:
        figure = new Circle();
    case 3:
        // etc...
        // Make a case for each valid number of sides
        // Don't forget to put a "break;" after each case!
        // Not a valid shape; print your error message
    return figure;

And let that factory method do the deciding instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download