Java 程序,创建字符串到超类类型映射


在这里,我们有一个超类 Vehicle,其中包含一些子类 −

class Vehicle {
}
class Motorcycle extends Vehicle {
}
class Bus extends Vehicle {
}
class Car extends Vehicle {
}

现在,我们将创建用于与超类类型映射的一些字符串 −

Map<String, Vehicle>map = new HashMap<String, Vehicle>();
map.put("motorcycle", new Motorcycle());
map.put("bus", new Bus());
map.put("car", new Car());

示例

 动态展示

import java.util.HashMap;
import java.util.Map;
class Vehicle {
}
class Motorcycle extends Vehicle {
}
class Bus extends Vehicle {
}
class Car extends Vehicle {
}
public class Demo {
   public static void main(String... args) {
      Map<String, Vehicle>map = new HashMap<String, Vehicle>();
      map.put("motorcycle", new Motorcycle());
      map.put("bus", new Bus());
      map.put("car", new Car());
      System.out.println(map);
   }
}

输出

{bus=my.Bus@97e1986, car=my.Car@26f67b76, motorcycle=my.Motorcycle@153f5a29}

更新于: 30-Jul-2019

130 次浏览

开启您的职业生涯

完成课程获得认证

开始
广告