Search code examples
javapolymorphismencapsulation

java-- Geometric shapes with polymorphism and encapsulation


Just to make sure this is my homework assignment. I need to implement classes to calculate area and perimeter of geometric shapes.

Overview of what I need: I will give something like "java ShapeTest Rectangle 5 5" in command line which should give area and perimeter of that rectangle.

Here is my code:

Shape.java

public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}

Rectangle.java

public class Rectangle extends Shape {
private double b;
private double a;

public Rectangle(){

}

public Rectangle(double a, double b) {
    this.a = a;
    this.b = b;
}

@Override
public double area(){
    return a *b;
}

@Override
public  double perimeter(){
    return 2*(a+b);
}

@Override
public String toString() {
    return "Rectangle{" +
            "a=" + a +
            " b=" + b +
            '}';
}
}

I have similar Circle, Triangle and Sqaure.java. This is my ShapeTest.java

public class FormenTest {


public static void set(){
//I want something here


}

public static void main(String[] args) {

    Rectangle rectangle = new Rectangle(Character.getNumericValue((args[1].charAt(0))),Character.getNumericValue((args[2].charAt(0))) );

    if(args[0].equals("Rectangle")){
        System.out.println(rectangle.area());

        }
    }
}

Now, this kind of does what is needed but I don't think this is nice way to do it. In the set method inside ShapeTest class I want to generate shape object which I later use in main method. Any help regarding optimizing the code and filling set method will be appreciated.


Solution

  • Your main method can look something like this:

    public static Shape createShape(String[] args) {
        Shape s = null;
        if(args.length > 0) {
            switch(args[0]) {
                case "Rectangle":
                    if(args.length > 2) {
                        s = new Rectangle(Double.parseDouble(args[1]), Double.parseDouble(args[2]));
                    }
                    break;
                case "Circle":
                    if(args.length > 1) {
                        s = new Circle(Double.parseDouble(args[1]));
                    }
                    break;
                case "Triangle":
                    //etc...
                    break;
            }
        }
        return s;
    }
    
    public static void main(String[] args) {
        Shape s = createShape(args);
    
        if(s != null) {
            System.out.println("Area: " + s.area());
            System.out.println("Perimeter: " + s.perimeter());
        }
    }
    

    }

    You will want to add user-friendly exception handling of course.