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.
CLASSES DIAGRAM:
--------------- Figure ---------------
^ ^ ^ ^
| | | |
| | | |
Circle Triangle Rectangle Exagone
MAIN CLASS:
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();
}
//...
else{
System.out.println("Error. Invalid sides number");
}
}
}
CLASSES CODE:
class Figure{
private int sides;
public Figure(int num_sides){
sides = num_sides;
}
}
class Circle extends Figure{
public Circle(){
super(0);
}
}
//... all the other classes has the same structure of Circle
A Java class constructor initializes instances (objects) of that class. Typically, the constructor initializes the fields of the object that need initialization. Java constructors can also take parameters, so fields can be initialized in the object at creation time.
In simple words, we can say that the parent constructor gets called first, then of the child class.
Parameterized Constructor – A constructor is called Parameterized Constructor when it accepts a specific number of parameters. To initialize data members of a class with distinct values.
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();
break;
case 3:
// etc...
// Make a case for each valid number of sides
// Don't forget to put a "break;" after each case!
default:
// Not a valid shape; print your error message
}
return figure;
}
And let that factory method do the deciding instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With