Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 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!!

Related questions

0 votes
1 answer
asked Jan 21, 2020 in Java by angadmishra (6.5k points)
0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...