Upcasting and Downcasting in java | Polymorphism-BasicITtopic

Upcasting and Downcasting in java

Upcasting and Downcasting:-

(Upcasting and Downcasting ) Java support Run-time polymorphism with the help of method overriding. Method overriding only applicable when the signature (prototype, return type, name, argument) of the superclass is the same as the subclass method, then it is known as method overriding.

  • Dynamic method dispatch allows Java to support overriding of methods that is the object of run-time polymorphism.
  • Overriding supports the concept of dynamic method dispatching. dynamic method dispatching possible by two different ways.
  1. Upcasting
  2. Downcasting

Upcasting

When the base class reference referred to the object of the child class is the concept of upcasting in Java.

Upcasting is not necessary. However, we need upcasting when we want to write general code that deals with only the supertype

Example

interface Test

{

      void show();

       void dis();

}

class Demo implements Test

{

    public void show()

    {

           System.out.println("show()....................");

     }

     public void dis()

      {

              System.out.println("dis().......................");

      }

      public void fun()
      {

              System.out.println("fun()...........................");

       }

       public static void main(String[] args)

        {

             Test t=new Demo();

             t.show();

              t.dis();

        }

}

Output :-

          show()....................

          dis().......................

Downcasting

When the subclass reference referred to the object of the superclass is known as downcasting in java.

When we want to access specific behaviors of a subtype downcasting is used.

Example

class Test

{



}

class Demo extends Test

{

     public static void main(String[] args)

     {

          Demo d1=(Demo)new Test();

           try

           {

                Demo d1=(Demo)new Test();

                                               

           }

           catch(ClassCastException)

           {

                    System.out.println("Down casting..........");

             }

    }

}
basicittopic

basicittopic

A Computer Science Study for IT students and people of IT community