Skip to content

Instantly share code, notes, and snippets.

@eleanor-em
Created September 4, 2019 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eleanor-em/9c5de4ec80f447994abc7120b869fe60 to your computer and use it in GitHub Desktop.
Save eleanor-em/9c5de4ec80f447994abc7120b869fe60 to your computer and use it in GitHub Desktop.
public class Program {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
sgihapes[0] = new Circle(0, 0, 1);
shapes[1] = new Rectangle(0, 0, 2, 1);
shapes[2] = new Circle(1, 1, 1);
for (Shape shape : shapes) {
System.out.println(shape.getArea());
}
}
}
public abstract class Shape {
private double x;
private double y;
public Shape(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public abstract double getArea();
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double x, double y, double width, double height) {
super(x, y);
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
class Circle extends Shape {
private double radius;
public Circle(double x, double y, double radius) {
super(x, y);
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public String toString() {
return "Centre: (" + getX() + ", " + getY() + "), radius: " + radius;
}
@Override
public boolean equals(Object rhs) {
if (rhs instanceof Circle) {
// Downcasting!
Circle other = (Circle) rhs;
return other.getX() == getX() && other.getY() == getY()
&& radius == other.radius;
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment