Last active
December 13, 2015 17:18
-
-
Save mepcotterell/4946494 to your computer and use it in GitHub Desktop.
Fun with Polymorphism
This file contains 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
*.class | |
*~ | |
\#*\# | |
semantic.cache |
This file contains 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 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 |
This file contains 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
/** | |
* 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 |
This file contains 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 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 |
This file contains 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 abstract class Shape { | |
public abstract double area(); | |
} // Shape |
This file contains 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 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