Complete and simple definitions of Up Casting, Down Casting, Implicit Casting and Explicit Casting

Nowadays I am preparing for the OCP, I’ve come to the topic of instanceof operator and casting in Java. I had obstacles in understanding the complete differences between Upcasting and Downcasting, so after a brief google search I’ve found very useful resources to apprehend the subject. Especially this post has given me such inspirational insights on the clear terms. Moreover related to the topic, I was also curious about the complete meanings of implicit and explicit castings and at this link I found really  clear description with sample code snippets  . All the terms seem to be identical at some point, and the below I try to explain as clearly as possible.

Implicit Casting:An implicit cast yields to that you don’t have to write code for the cast

int i = 999999999;
float f = i;    // An implicit conversion is performed here

Explicit Casting: An explicit cast dictates that you are responsible of providing the cast

int i = 999999999;
byte b = (byte) i;  // The type cast causes an explicit conversion
b = i;

 

enter image description here

Up casting: Done by the compiler automatically, this is to cast the base object to the derived object

Down casting: Done by the programmer manually.

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 ExampleMain
{
    public static void main (String [] args) 
    {
      Dog d = new Dog();
// Explict you have done upcasting. Actually no need, we can directly
// type cast like Animal a = d;
Animal a = (Animal) d; // upcasting: compiler now treat Dog as Animal
                        // but still it is Dog even after upcasting
d.callme();
a.callme(); // It calls Dog's method even though we use Animal
            // reference.
((Dog) a).callme2(); // downcasting: compiler does know Animal it is, In
                        // order to use Dog methods, we have to do
                        // typecast explicitly.
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *