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

Java 8Object Oriented ProgrammingProgramming

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();
   }
}


raja
Published on 02-Jan-2018 07:02:54
Advertisements