Popular Feed

Down Casting and Up Casting in java

What is casting?


Casting means, Converting one data type to another type.

There are two ways inheriting the properties of the parent and child classes. 

 Basically, we will discuss here about DownCasting and UpCasting 

  down casting up casting java



Up-casting when we convert (Cast) subclass type to a Superclass type, it known as up-casting.

Upcasting can be done implicitly. 


class SuperClass {
   void Sample() {
      System.out.println("This is super class");
   }
}
public class SubClass extends SuperClass {
   void Sample() {
      System.out.println("This is sub class");
   }
   public static void main(String args[]) {
     SuperClass obj = new SubClass();     
     obj.Sample();             
   }
}

Out PUT-:

This is sub Class

Down-casting when we convert (Cast) Superclass type to a Subclass type, it known as down-casting.

Example

class SuperClass {
   void Sample() {
      System.out.println("This is super class");
   }
}
public class SubClass extends SuperClass {
   void Sample() {
      System.out.println("This is sub class");
   }
   public static void main(String args[]) {
      SuperClass obj = new SubClass();
      SubClass sub = (SubClass) obj; 
      sub.Sample();
   }
}

Out PUT-:

This is sub Class


No comments: