Java: using polymorphism to avoid if-statements?

Viewed 9989

I'm attempting to write a java program that initializes certain layouts based on what the user selects. What I want to do is try to avoid writing a bunch of if-statements so the code can be scalable for future use if more layouts need to be added. I heard the best way to implement this is using polymorphism but my understanding of polymorphism is still a little fuzzy.

Say I want to implement this case:

if (user choose layoutA) { initialize layoutA }
if (user choose layoutB) { initialize layoutB }
if (user choose layoutC) {initialize layoutC }

I was thinking of creating an interface for classes to implement. What confuses me is how it works in main(), won't I still need a conditional if or switch statement to figure out which class to instantiate?

interface LayoutHandler {
    public void initializeLayout();
}

class layoutA implements LayoutHandler { 
    public void initialize Layout {initialize layout A}
}
class layoutB implements LayoutHandler { 
    public void initialize Layout {initialize layout B}
}
class layoutC implements LayoutHandler { 
    public void initialize Layout {initialize layout C}
}

Then somewhere out in main:

public static void main() {
   getlayoutselectionfromuser()
   if (user choose layoutA) { LayoutHandler layout = new layoutA(); }
   if (user choose layoutB) { LayoutHandler layout = new layoutB(); }
   if (user choose layoutC) { LayoutHandler layout = new layoutC(); }

}

Wouldn't I still require a switch or if-statement in the main program to figure out which layout the user has chosen during runtime?

Thanks!

9 Answers
Related