What is upcasting and downcasting in the Java language?

Asked

Viewed 8,059 times

19

What would be downcasting and upcasting in Java? Examples please.

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to do this. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

2 answers

21

Upcasting is to make an object pass through an object that is a supertype of it. It will always work since every object is fully compatible with a type from which it was derived. As can always be accomplished, it is possible to do implicitly, ie the compiler does it for you when it is necessary.

It is very common for it to occur as a parameter of a method that will use polymorphism. The caller sends as argument an object that is the subtype, the method receives a parameter as if it were the supertype, but acts as a subtype. But note that polymorphism is an auxiliary mechanism and not directly linked to casting. It is considered a compilation-time coercion.

Some people like to call it a type promotion.

Downcasting is when the object passes as if it were a subtype of it. There are no guarantees that work (you can launch a ClassCastException, which is obviously a programming error) and there may be a need for conversions. The compiler accepts only if he can prove that the object fits perfectly and is in fact that object. Therefore it should be made explicit by the programmer when he wants this action. Coercion occurs at runtime.

Some people like to call it a type demotion (despite being a neologism).

There is a pattern normally used to avoid the exception when not sure it will work:

obj instanceof Tipo ? (Tipo)obj : null

In this example if the object is not of the appropriate type, it will create a null and will not attempt the cast. Obviously any attempt to access the generated object will be problematic, so it is necessary to verify if the object is null before trying to access it, otherwise it will only change error.

Examples:

class Animal { 
    public void fazBarulho() {
        System.out.println("silêncio");
    }
}
class Dog extends Animal { 
    public void fazBarulho() {
        System.out.println("au au");
    }
}
class Cat extends Animal { 
    public void fazBarulho() {
        System.out.println("miau");
    }
}
class Ideone {
    public static void main(String[] args) {
        Dog dog = new Dog();      
        Animal animal = new Animal();
        Animal animal2 = new Dog();
        Animal animal3 = new Cat();
        dog.fazBarulho();
        animal.fazBarulho();
        animal2.fazBarulho(); //concretamente é um cachorro
        animal3.fazBarulho(); //concretamente é um gato
        System.out.println("-- Castings agora --");
        ((Animal)dog).fazBarulho(); //upcasting
        ((Dog)animal2).fazBarulho(); //downcasting, funciona
        ((Dog)animal3).fazBarulho(); //downcasting, dá erro porque um gato não é um cachorro
        ((Dog)animal).fazBarulho(); //downcasting, dá erro aqui
    }
}

Behold "working" in the ideone. And in the repl it.. Also put on the Github for future reference.

When there is no guarantee that the object will have all that is expected of that type, the cast will fail. This is the obvious case of a cat trying to pass itself off as a dog. When the generic animal tries to pass itself off as a dog, neither does it. While coincidentally in this example might even work, the compiler cannot prove this. The programmer who is looking at all the code knows, but he will not always be able to see all the classes. What’s more, it is possible for maintenance to modify the class and what worked to stop working. So you have to go the safe way.

In general this works the same in all languages that have inheritance.

10

To better understand these concepts you need to first understand the concepts of INHERITANCE, 'BEING ONE' and POLYMORPHISM. Come on...

Inheritance

Classes Cat and Leao inherit the Feline class, so Cat and Leao are felines.

'Be a'

Cat is a cat. Simple as that. rs

Polymorphism (be more of a')

Cat, besides being a cat, is also a feline, so Cat is polymorphic.

Upcasting (rise)

It is when a superclass receives a reference from the subclass. Implicit, for cat IS A feline.

Ex:

Gato g = new Gato();
Felino f = g;

Downcasting (lower the hierarchy)

It’s when a subclass gets a reference from a superclass. Not implicit, because the compiler does not know if the instance is really the type of subclass declared, because, as in this example, Felino can be a cat or a Leao. But as the programmer knows it is cat-like, he puts the subclass in parentheses, indicating to the compiler that the casting is correct.

Ex:

Felino f = new Gato();
Gato g = (Gato) f;

Note: if casting is not correct, the exception occurs ClassCastException

Ex:

Felino f = new Leao();
Gato g = (Gato) f;
  • 1

    Thanks, Bruno! You helped me!

  • Imagine, any doubt just ask ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.