Pin It

Java Polymorphism : Example to show Upcasting in Java

Program to demonstrate how upcasting works in Java through Polymorphism.

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 : 


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot