Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me with the difference between up-casting and down-casting wrt class variable? In the below example how I can able to cast the dog variable to the animal variable?

class Animal 

    public void callme()

    {

        System.out.println("In callme of Animal");

    }

}

class Dog extends Animal 

    public void callme()

    {

        System.out.println("In callme of Dog");

    }

    public void callme2()

    {

        System.out.println("In callme2 of Dog");

    }

}

public class UseAnimlas 

{

    public static void main (String [] args) 

    {

        Dog d = new Dog();      

        Animal a = (Animal)d;

        d.callme();

        a.callme();

        ((Dog) a).callme2();

    }

}

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

Basically, upcasting is a casting of supertype whereas, downcasting is a casting of subtype. While doing downcasting it will involve a type check and can also throw an exception called ClassCastException.

For this case, upcast can be done because the dog is an animal. Also, you can do an upcast where there is an is-a relationship available between two classes. If you want to do the downcasting then this will look like this:

Animal animal = new Dog();

Dog castedDog = (Dog) animal;

I hope this will help.

Want to become a Java Expert? Join Java Course now!!

Browse Categories

...