Skip to content

Instantly share code, notes, and snippets.

@mepcotterell
Last active December 13, 2015 17:18
Show Gist options
  • Save mepcotterell/4946494 to your computer and use it in GitHub Desktop.
Save mepcotterell/4946494 to your computer and use it in GitHub Desktop.
Fun with Polymorphism
*.class
*~
\#*\#
semantic.cache
public class Circle extends Shape {
int radius;
public Circle(int radius) {
this.radius = radius;
} // Circle
@Override
public double area() {
return Math.PI * this.radius * this.radius;
} // area
} // Circle
/**
* Driver for the Polymorphism Examples
*
* @author Michael E. Cotterell <mepcotterell@gmail.com>
*/
public class Driver {
public static void main(String[] args) {
Shape c = new Circle(10);
Shape r = new Rectangle(10, 30);
Shape s = new Square(20);
Shape[] array = new Shape[] { c, r, s };
for (Shape shape: array) {
System.out.println("area is " + shape.area());
}
} // main
} // Driver
public class Rectangle extends Shape {
int length, width;
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
} // Rectangle
@Override
public double area() {
return length * width;
} // area
} // Rectangle
public abstract class Shape {
public abstract double area();
} // Shape
public class Square extends Rectangle {
public Square(int length) {
super(length, length);
} // Square
} // Square
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment