日期:2014-05-20  浏览次数:20901 次

强制类型转换和多态的疑问
疑问就是代码里注释的那一行,ob已经是Integer类型了,为什么还要转换一下
Java code

public class GenDemo2
{
  public static void main(String[] args)
  {
      Gen2 intOb = new Gen2(new Integer(88));
      intOb.showType();
      //Integer i = intOb.getOb(); 如果不做强制类型转化就会报错,可是多态不就能解释的通可以不用强制类型转换。
      Integer i = (Integer)intOb.getOb();
  }
}

class Gen2
{
    private Object ob;
    public Gen2(Object ob)
    {
        this.ob = ob;
    }
    public Object getOb()
    {
        return ob;
    }
    public void setOb(Object ob)
    {
        this.ob = ob;
    }
    public void showType()
    {
        System.out.println("T的实际类型是:"+ ob.getClass().getName());
    }
}



------解决方案--------------------
public Object getOb()
{
return ob;
}

返回的是Object类型的必须强制转型
------解决方案--------------------
lz再理解理解多态的含义吧
http://blog.csdn.net/renyuanchunby/article/details/6967860