interface Shape {
public double area();
}
class Circle implements Shape {
private double radius;
public Circle(double r){radius = r;}
public double area(){return Math.PI*radius*radius;}
}
class Square implements Shape {
private int wid;
public Square(int w){wid = w;}
public double area(){return wid *wid;}
}
public class Poly{
public static void main(String args[]){
Shape[] s = new Shape[2];
s[0] = new Circle(10);
s[1] = new Square(10);
System.out.println(s[0].getClass().getName());
System.out.println(s[1].getClass().getName());
}
}
In an effort to understand the concept of polymorphism, I found the following post (https://stackoverflow.com/a/4605772/112500) but I noticed that Charlie created the Shape class with a unimplemented method.
As one can see from my code, I converted that class into an interface and then used it to instantiate an anonymous class which then called the appropriate method.
Could someone tell me if my solution is sound? Would you have written the code in a different manner? Why does the use of an interface on both sides of the equal sign function as it does?
Thanks.
Caitlin