Created
September 4, 2019 03:57
-
-
Save eleanor-em/20b7739c495a7274f47c9c6f899b2928 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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