import java.util.*;
class TestMap
{
public static void main(String args[])
{
Map mp = new HashMap();
mp.put("1",new Integer(123));
mp.put("2",new Integer(456));
mp.put("3",new Integer(789));
System.out.println(mp);
}
}
加红的地方为什么可以这样使用?可以说说多态吗?
class TestMap
{
public static void main(String args[])
{
Map mp = new HashMap();
mp.put("1",new Integer(123));
mp.put("2",new Integer(456));
mp.put("3",new Integer(789));
System.out.println(mp);
}
}
加红的地方为什么可以这样使用?可以说说多态吗?
因为向上转型后mp调用了HashMap中的方法,与Map中的无关;如果Map还有其他的实现类,就调用相应的其他类中的方法,Map mp 这个大的类型不用改变。体现了多态。
相当于:
人 makesi = new 马克思();“马克思”是“人”的一个派生类,“makesi”是“马克思”的一个实例。
是不能够直接创建对象的!
多态实现指的是使用同一个实现接口,以实现不同的对象实例.
可以试试:Map<String,Integer> mp = new HashMap<String,Integer>();