A Situation in which Downcasting could occur is in the context of the factory design pattern. In this design pattern the implementation details of multiple child classes can be abstracted by just using their parent class.
Consider the following example:
import java.util.ArrayList;
public class Factory {
private ArrayList products = new ArrayList();
public static void main(String[] args){
Factory factory = new Factory();
factory.addProduct(new Ball("1"));
factory.addProduct(new ToyCar("2"));
factory.addProduct(new Dice("3"));
Product popProduct = factory.popProduct();
Ball downcastBall = (Ball)popProduct;
System.out.println(downcastBall.getId());
}
public void addProduct(Product prodIn){
products.add(prodIn);
}
public Product popProduct(){
Product returnProd = products.get(0);
products.remove(0);
return returnProd;
}
}
The classes Ball, ToyCar and Dice all extend the Product class and implement the getId() method of it, so the three children can all be treated as just Products. This is called a polymorphism.
I Post the rest of the code so you can play around with it.
The Ball class:
public class Ball extends Product{
public Ball(String id) {
super(id);
}
public String getId(){
return "ball!";
}
}
The ToyCar class:
public class ToyCar extends Product{
private String ToyCarId;
public ToyCar(String id) {
super(id);
}
public String getId(){
return this.ToyCarId;
}
}
The Dice class:
public class Dice extends Product{
private String diceId;
public Dice(String id) {
super(id);
}
public String getId(){
return this.diceId;
}
}
And finally the Product class:
public class Product {
private String id;
public Product(String id){
this.id = id;
}
public String getId(){
return this.id;
}
}