Skip to content

Instantly share code, notes, and snippets.

/Circle Secret

Created October 23, 2013 13:19
Show Gist options
  • Save anonymous/0760d154f81064bf8493 to your computer and use it in GitHub Desktop.
Save anonymous/0760d154f81064bf8493 to your computer and use it in GitHub Desktop.
Polymorphic code
public class Circle extends Shape
{
public Circle(double length) {
super(length);
}
@Override
public double getArea()
{
return length * length * Math.PI;
}
@Override
public double getBoundaryLength() {
return 2 * length * Math.PI;
}
}
import java.util.Scanner;
public class MyShapes
{
public static Scanner scan = new Scanner(System.in);
public static int Menu()
{
System.out.println("\nSelect a Shape or Exit: \n");
System.out.println("1. Square");
System.out.println("2. Circle");
System.out.println("3. Triangle");
System.out.println("4. Exit");
System.out.println("\nEnter choice:");
int option = scan.nextInt();
return option;
}// end menu
public static void main(String[] args)
{
int option = 0;
while (option != 4)
{
option = Menu();
switch(option)
{
case 1:
Shape shape = new Circle(scan.nextDouble());
double boundaryLength = shape.getBoundaryLength();
double area = shape.getArea();
System.out.println("Boundary Length = " + Math.round(boundaryLength));
System.out.println("Area = " + Math.round(area));
break;
case 2:
Shape shape1 = new Square(scan.nextDouble());
double boundaryLength1 = shape1.getBoundaryLength();
double area1 = shape1.getArea();
System.out.println("Boundary Length = " + Math.round(boundaryLength1));
System.out.println("Area = " + Math.round(area1));
break;
case 3:
Shape shape2 = new Triangle(scan.nextDouble());
double boundaryLength2 = shape2.getBoundaryLength();
double area2 = shape2.getArea();
System.out.println("Boundary Length = " + Math.round(boundaryLength2));
System.out.println("Area = " + Math.round(area2));
break;
case 4:
System.out.println("System closing");
System.out.println("-----------\n");
System.exit(0);
break;
default:
System.out.println("Invalid option");
System.out.println("--------------\n");
}
}
}
}
public abstract class Shape
{
protected double length;
public Shape(double length)
{
this.length = length;
}
public abstract double getArea();
public abstract double getBoundaryLength();
}
public class Square extends Shape
{
public Square(double length) {
super(length);
}
@Override
public double getArea()
{
return length * length;
}
@Override
public double getBoundaryLength()
{
return length * 4;
}
}
public class Triangle extends Shape
{
public Triangle(double length) {
super(length);
}
@Override
public double getArea()
{
return 0.5 * length * length;
}
@Override
public double getBoundaryLength()
{
return (length + length) + Math.sqrt(2 * length * length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment