In this blog, we will learn about Downcast and Upcast with the help of a simple example.
Let us first learn what Downcast is. Downcast, as the name suggests, is the process of going down from the top. Yes, it means going from top to bottom, i.e, from Super class to Sub class.
Now, let us come to an example in order to understand it better. The very basic rule in casting that we should never forget is that - "A child class can always refer to its parent class but the parent class can't refer to its child class."
Example
Suppose, we have 3 classes - Parent, Child, and another child (Sibling) in such a way that Child extends Parent and Child's child (sibling) extends Child.
Case1
- Parent parent = new Child();
- Child child = (Child) parent;
- child.sleep();
Now,
- Sibling sibling = (Sibling) child
- sibling.cry();
Which means something like this,
- Child child = new Parent();
Use Case2
- Parent parent = new Sibling();
- Child child = (Child) parent;
- Sibling sibling = (Sibling) child;
- sibling.walk();
This will work because we have cast parent to child and then child to sibling.
Use Case3
- Parent parent = new Child();
- parent = new Sibling();
- Child child = (Child) parent;
- child.sleep();
Upcast
We need to remember that in this type of casting, we need not explicitly cast the object as we are going upwards to the parent class. So, the access to the number of methods will be restricted automatically.
Example
- Child child = new Child();
- Parent parent = (Parent) child;
- Parent parent = child;
- parent.work();
But if we try to invoke child class method here, we will get an error because at compile time, it will check the reference variable which is of type parent but the method we are trying to call is of child class.
So, the compiler will check parent class and won’t find that method. Then, it will throw error.