java type casting,Type casting/Down casting in Java

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值