Override Shape : Override Polymorphism « Class « Java






Override Shape

Override Shape

// : c10:Shapes.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.

class Shape {
  void draw() {
    System.out.println(this + ".draw()");
  }
}

class Circle extends Shape {
  public String toString() {
    return "Circle";
  }
}

class Square extends Shape {
  public String toString() {
    return "Square";
  }
}

class Triangle extends Shape {
  public String toString() {
    return "Triangle";
  }
}

public class Shapes {

  public static void main(String[] args) {
    // Array of Object, not Shape:
    Object[] shapeList = { new Circle(), new Square(), new Triangle() };
    for (int i = 0; i < shapeList.length; i++)
      ((Shape) shapeList[i]).draw(); // Must cast

  }
} ///:~


           
       








Related examples in the same category

1.Polymorphism in JavaPolymorphism in Java
2.It only looks like you can override a private or private final methodIt only looks like you can override a private or private final method
3.Method override demoMethod override demo