Program to demonstrate how upcasting works in Java through Polymorphism.
Output of the program :
class Shape { public void draw(Shape s){ System.out.println("Shape drawn ... " + s); } @Override public String toString() { return "Shape drawn with Shape Object"; } } class Triangle extends Shape{ public void draw(Shape s){ System.out.println("Shape drawn ... " + s); } @Override public String toString() { return "Shape drawn with Triangle Object"; } } public class UpcastingTest { public static void main(String[] args) { Shape s = new Shape(); s.draw(s); Triangle t = new Triangle(); t.draw(t); Shape st = new Triangle(); st.draw(st); /*Triangle ts = (Triangle) new Shape(); ts.draw(ts);*/ // Runtime error Shape cannot // be cast to Triangle } }
Output of the program :