为什么我的构造函数不起作用? (JAVA)

时间:2015-08-05 18:11:39

标签: java oop selenium constructor

我有以下类实现

public class PublisherHashMap
{
     private static HashMap<Integer, String> x;

     public PublisherHashMap()
     {
         x.put(0, "www.stackoverflow.com");
     }
}

在我的测试功能中,由于某种原因,我无法创建对象。

@Test
void test()
{ 
   runTest();
}

public static void runTest()
{
    PublisherHashMap y = new PublisherHashMap();
}

编辑:我没有构建HashMap。

2 个答案:

答案 0 :(得分:7)

您正在尝试使用x私有HashMap,然后才构建它。因此,您需要先构建它。您可以通过以下任何方式执行此操作:

1)在构造函数中:

x = new HashMap<Integer, String>(); 
// or diamond type  
x = new HashMap<>();

2)在课堂上作为这个班级的一个领域:

private static HashMap<Integer, String> x = new HashMap<>();

3)在初始化程序块中:

static { 
    x = new HashMap<>();
}
// or the no-static block
{
    x = = new HashMap<>();
}

答案 1 :(得分:2)

您必须从

更改声明
private static HashMap<Integer, String> x;

private static HashMap<Integer, String> x = new HashMap<Integer, String>();
相关问题