Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

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 : 


 
© 2021 Learn Java by Examples Template by Hubberspot