Java Program to create String to super class type mapping

Java 8Object Oriented ProgrammingProgramming

Here, we have a superclass Vehicle and within that some subclasses −

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

Now, we will create some strings for mapping with super class type −

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

Example

 Live Demo

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);
   }
}

Output

{bus=my.Bus@97e1986, car=my.Car@26f67b76, motorcycle=my.Motorcycle@153f5a29}
raja
Published on 25-Apr-2019 12:31:57
Advertisements