Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • Difference between Upcasting and Downcasting

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.01k
    Comment on it

    Casting in Java

    Follwing Blog is about Upcasting and Downcasting In Java.
    Upcasting
    Upacsting Is a concept used to support Runtime Polymorphism in which Parent Class refernce variable can hold child value
    Syntax

    A ob=new B(); // Memory of B is allocated to Object of A
    


    It is to be Noted that Upcasting Never Fails. When we are upcasting we can use only method or function which is a part of parent but called through child object.
    Downcasting
    Downcasting is also a way to casting reference of Child Class to one of its Parent Class

    B ob=(A)x;  // Instance of A is allocated to B Object
    

    It Is to be noted that Downcasting may Fails.

    Following Program helps you to clear all doubts u are having...

    public class A {
        public void Show()
        {
            System.out.println("Calling from A's Show()");
        }
    
    }
    public class B {
        public void Show()
        {
            System.out.println("Calling from B's Show()");
        }
        public void Display()
        {
            System.out.println("Calling from B's display()");
        }
    
    }
    public class Demo {
        public static void main(String ar[])
        {
            A x=new B(); // Upcasting
            x.show();
            B y=(B)x; // Downcasting
            y.Display();
        }
    }
    
    Java

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: