What would be downcasting and upcasting in Java? Examples please.
What would be downcasting and upcasting in Java? Examples please.
Upcasting is to make an object pass through 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 accomplished, it is possible to do so implicitly, ie the compiler does for you when needed.
It is very common for it to occur as a parameter to a method that will use polymorphism. The caller calls as an argument an object that is the subtype, the method receives a parameter as if it were the supertype, but functions as a subtype. But note that polymorphism is an auxiliary mechanism and not directly linked to casting . It is considered compile-time constraint.
Some people like to call it type promotion.
Downcasting is when the object passes as if it were a subtype of it. There are no guarantees that it works (you can cast ClassCastException
, which obviously is a programming error) and there may be a need for conversions. The compiler only accepts if it can prove that the object will fit perfectly and is in fact that object. Therefore it should be explained by the programmer when you want this action. Coercion occurs at runtime.
Some people like to call it a type demo (though it's a neologism).
There is a pattern normally used to avoid the exception when you are not sure which 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 try cast . Obviously any attempt to access the generated object will be problematic, so you need to check if the object is null before attempting 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
}
}
See "working on ideone" and on CodingGround a>.
When there is no guarantee that the object will have everything expected of that type, 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 a dog, it does not. Although coincidentally in this example might even work, the compiler can not 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's possible for a maintenance to modify the class and what works did not work. So you have to go the safe way.
In general this works the same in all languages that have inheritance.
To better understand these concepts you must first understand the concepts of HERITAGE, 'BEING ONE' and POLYMORPHISM. Come on ...
Inheritance
Cat and Lion classes inherit the Feline class, so Cat and Lion are feline.
'Being one'
Cat is a cat. That simple. rs
Polymorphism (be more 'one')
Cat, besides being a cat, is also a Cat, so Cat is polymorphic.
UpCasting (up the hierarchy)
This is when a superclass receives a subclass reference. Implicit, therefore cat IS A feline.
Ex:
Gato g = new Gato();
Felino f = g;
DownCasting (go down the hierarchy)
This 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 declared subclass type, because, as in this example, Feline can be a cat or a Lion. But as the programmer knows it's cat-like, it puts the subclass in parentheses, telling the compiler that Casting is correct.
Ex:
Felino f = new Gato();
Gato g = (Gato) f;
Note: if the casting is not correct, the exception ClassCastException
Ex:
Felino f = new Leao();
Gato g = (Gato) f;