1

What is the difference between the up-casting and down-casting with respect to primitive datatypes and referenced datatypes.

For example in primitive types we are saying up-casting is going from lower to higher (int to double) and down-casting is higher to lower(double to int). For this we use cast operator.

But for referenced data types it is in opposite of the previous case. For example animal only contains callme() method but dog contains callme() and callme2() methods then how we can say that animal is higher than dog.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Dhivakar
  • 2,081
  • 5
  • 15
  • 18
  • Does this answer your question? [What is the difference between up-casting and down-casting with respect to class variable](https://stackoverflow.com/questions/23414090/what-is-the-difference-between-up-casting-and-down-casting-with-respect-to-class) – jayanthsaikiran Dec 09 '19 at 05:57

1 Answers1

1

@user3316746:

Let's use your example of animal and dog, but also throw cat into the mix.

Animal is an abstract class that would never be instantiated, and is meant to hold common attributes and behaviours of the classes that inherit from it. So, in this case, the animal class might look like:

class Animal {

    // Properties (attributes)
    private int age;

    // Methods (behaviours)
    public void eat();
    public void sleep();
}

Both dog and cat inherit the 'age' property and the 'eat' and 'sleep' methods defined in the 'animal' class, but they can also define new properties and new behaviours specific to that type of animal.

So cat could look like:

class Cat extends Animal {

    // Methods (behaviours)
    public void purr();
}

And dog could look like:

class Dog extends Animal {

    // Methods (behaviours)
    public void bark();
}

So both dog and cat are types of animals, they both have an age, and they can both eat and sleep. However, only a cat can purr and only a dog can bark.

The dog and cat classes have more functionality than the base animal class they inherit from, but the animal class is still considered higher because it defines attributes and behaviours that are common to both cats and dogs.

trevor
  • 2,300
  • 1
  • 14
  • 13