The following code appears in Main.java :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
class Polygon { int sides; public Polygon(int sides){ this.sides = sides; } protected String getName(){ return "Polygon"; } public void printDescription(){ System.out.println(getName() + " has " + sides + " sides"); } } class Square extends Polygon { int sideLength; public Square(int sideLength) { super(4); this.sideLength = sideLength; } @Override protected String getName(){ return "Square"; } @Override public void printDescription(){ super.printDescription(); System.out.println("It has side length: " + sideLength); } } class Triangle extends Polygon { double side1, side2, side3; public Triangle(double side1, double side2, double side3) { super(3); this.side1 = side1; this.side2 = side2; this.side3 = side3; } @Override protected String getName(){ return "Triangle"; } @Override public void printDescription(){ super.printDescription(); System.out.println("It has side lengths: " + side1 + ", " + side2 + ", " + side3); } } public class Main { public static void main(String[] args) { Polygon poly = new Polygon(5); Square square = new Square(10); Triangle tri = new Triangle(2.3, 1.7, 3.4); poly.printDescription(); System.out.println(); square.printDescription(); System.out.println(); tri.printDescription(); } } |
It produces the following output:
1 2 3 4 5 6 7 |
Polygon has 5 sides Square has 4 sides It has side length: 10 Triangle has 3 sides It has side lengths: 2.3, 1.7, 3.4 |