javacollectionshashmapjava-collections-api

Different ways to initialize and put objects to HashMaps


I've been playing around with HashMaps and realized that instantiating HashMaps in a class that has main() behaves differently when instantiated in a class that doesn't have main.

Demo.java

import java.util.HashMap;

public class Demo {

public static void main(String args[]) {
        System.out.println(new Circle());

        HashMap<String, Object> shapes = new HashMap<String,Object>();
        shapes.put("Circle", new Circle());
    }
}

GeometricObject.java

import java.util.HashMap;

abstract class GeometricObject
{   
    HashMap<String, Object> shapes = new HashMap<String,Object>(); //error
    shapes.put("Circle", new Circle()); //error
}

What is a correct way to initialize a HashMap in a class that doesn't have a main()?


Solution

  • shapes.put("circle", new Circle());
    

    This code is not in a method or in a static block. This code can not be executed freely in the body of a class. This will cause a compilation error.