Java程序创建String到超类类型的映射
在这里,我们有一个超类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}