0

How do I do something like this? I want to take command line arguments like Circle 10 or Rectangle 20 30 and create objects of the corresponding classes.

class Circle{
    //Some lines here
}

class Rectangle{
    //Some lines here
}

public class Perimeter{
    public static void main(String[] args) {
        for(int i=0; i< args.length; i++){
            String shape = args[0];
            shape curr_shape = new shape();
            System.out.println(curr_shape.getPerimeter( <arguments> ));
        }
    }
}

Jay Sinha
  • 45
  • 6
  • Does this answer your question? [Create new object from a string in Java](https://stackoverflow.com/questions/1268817/create-new-object-from-a-string-in-java) – Milgo Sep 24 '20 at 05:46
  • I have created all the classes I need. I need to create objects of those classes using variables. I think the link describes how to create classes with string. – Jay Sinha Sep 24 '20 at 05:54

2 Answers2

2

You can use Class.forName() and reflection to create an instance, like @Milgo proposed, but I would recommend to create a simple switch/case. Your task looks like some training, so probably that would be best option for you.

Object form;
switch (type) {
  case "Circle":
    form = new Circle();
    break;
  case "Rectangle":
    form = new Rectangle();
    break;
}
  • 1
    Additionally you could have an abstract base class `Form` with an abstract `getPerimeter()` method, which Circle, Rectangle etc. implement. Then change `Object form` to `Form form` and have a `return form.getPerimeter()` at the end. – Ridcully Sep 24 '20 at 06:07
1

Although you could use reflection (ie the dark arts), you can do it with minimal code if all shapes have the same constructor signature of say List<Double> (which includes integers like your example):

private static Map<String, Function<List<Double>, Shape>> factories = 
    Map.of("Circle", Circle::new, "Rectangle", Rectangle::new); // etc

public static Shape createShape(String input) {
    String[] parts = input.split(" ");
    String name = parts[0];
    List<Double> dimensions = Arrays.stream(parts)
      .skip(1) // skip the name
      .map(Double::parseDouble) // convert String terms to doubles
      .collect(toList());
    return factories.get(name).apply(dimensions); // call constructor
}

interface Shape {
    double getPerimeter();
}

static class Rectangle implements Shape {
    private double height;
    private double width;

    public Rectangle(List<Double> dimensions) {
        height = dimensions.get(0);
        width = dimensions.get(1);
    }

    @Override
    public double getPerimeter() {
        return 2 * (height + width);
    }
}

static class Circle implements Shape {
    double radius;

    public Circle(List<Double> dimensions) {
        radius = dimensions.get(0);
    }

    @Override
    public double getPerimeter() {
        return (double) Math.PI * radius * radius;
    }
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722