What are up-casting and down-casting in Java?


Typecasting is converting one data type to another.

Up-casting − Converting a subclass type to a superclass type is known as up casting.

Example

class Super {
   void Sample() {
      System.out.println("method of super class");
   }
}

public class Sub extends Super {
   void Sample() {
      System.out.println("method of sub class");
   }
   
   public static void main(String args[]) {
      Super obj =(Super) new Sub(); obj.Sample();
   }
}

Down-casting − Converting a superclass type to a subclass type is known as downcasting.

Example

class Super {
   void Sample() {
      System.out.println("method of super class");
   }
}

public class Sub extends Super {
   void Sample() {
      System.out.println("method of sub class");
   }

   public static void main(String args[]) {
      Super obj = new Sub();
      Sub sub = (Sub) obj; sub.Sample();
   }
}


Updated on: 18-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements