What is Upcasting and downcasting in the Java language?

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

Author: Maniero, 2016-05-29

2 answers

Upcasting it is to make an object if it passes by an object that is a supertype of it. It will always work since every object is completely compatible with a type from which it was derived. As it can always be realized, it is possible to do implicitly, that is, the compiler does it for you when it is needed.

It is very common 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 it works as a subtype. But note that polymorphism is an auxiliary mechanism and not directly linked to casting . It is considered a compiling time coercion.

Some people like to call it type promotion.

Downcasting that's when the object passes as if it were a subtype of it. There are no guarantees that it will work (it can throw a ClassCastException, which is obviously a programming error) and there may be need for conversions. The compiler only accepts if it can prove that the object will fit perfectly and is indeed that object. So it must be explained by the programmer when he wants this action. Coercion occurs at runtime.

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

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

obj instanceof Tipo ? (Tipo)obj : null

In this example if the object does not if it is of the appropriate type, it will create a null and neither will it attempt the cast. Obviously any attempt to access the generated object will be problematic, so you have to check if the object is null before trying to access it, otherwise it will only exchange errors.

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
    }
}

See "working" on ideone. E no repl.it. also I put on GitHub for future reference .

When there are no guarantees that the object will have everything expected of that type, cast will fail. It is the obvious case of a cat trying to impersonate a dog. When the generic animal tries to impersonate a dog, it also does not give. Although coincidentally this example might even work, the compiler cannot prove this. The programmer who is seeing all the code knows, but he will not always be able to see all the classes. What's more, it is possible a maintain modify the class and what worked stop working. Then you have to go the safe way.

Generally speaking this works the same in all languages that have inheritance.

 19
Author: Maniero, 2020-10-27 17:05:07

To better understand these concepts you first need to understand the concepts of inheritance,' being one ' and polymorphism. Come on...

Inheritance

Classes cat and Lion inherit the Class feline, so cat and Lion are felines.

'Be A'

Cat is a cat. Simple as that. rs

Polymorphism (be more 'than one')

Cat, in addition to being a cat, is also a feline, so cat is polymorphic.

UpCasting (move up the hierarchy)

Is when a superclass receives a reference from the subclass. Implied, for cat is a feline.

Ex:

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

DownCasting (down to hierarchy)

Is when a subclass receives a reference from a superclass. Not implicit, because the compiler does not know if the instance is actually of the type of the declared subclass, since, as in this example, feline can be a cat or a lion. But how the programmer knows that it is cat type, he puts the subclass in parentheses, indicating to the compiler that the Casting is correct.

Ex:

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

Obs.: if the casting is not correct, the excess ClassCastException

Ex:

Felino f = new Leao();
Gato g = (Gato) f;
 10
Author: Bruno Silva, 2016-11-21 19:02:25