No enclosing instance of type HashMapTest is accessible. Must qualify the allocation with an enclosi

No enclosing instance of type HashMapTest is accessible. Must qualify the allocation with an enclosing instance of type HashMapTest (e.g. x.new A() where x is an instance of HashMapTest).
代码如下:
public class HashMapTest {

public static void main(String[] args) {
	Employee e1=new Employee(1000, "aa", 110000);
	Employee e2=new Employee(1001, "ab", 30000);
	Employee e3=new Employee(1002, "ac", 32000);
	Employee e4=new Employee(1003, "ad", 60000);
	
	Map<Integer, Employee> map1=new HashMap<>();
	map1.put(1000, e1);
	map1.put(1001,e2);
	map1.put(1002, e3);
	map1.put(1003, e4);
	Employee emp=map1.get(1001);
	System.out.println(emp);
}
	
	class Employee{
		private int id;
		private String ename;
		private double salary;
		
		
		public Employee(int id, String ename, double salary) {
			super();
			this.id = id;
			this.ename = ename;
			this.salary = salary;
		}


		public int getId() {
			return id;
		}


		public void setId(int id) {
			this.id = id;
		}


		public String getEname() {
			return ename;
		}


		public void setEname(String ename) {
			this.ename = ename;
		}


		public double getSalary() {
			return salary;
		}


		public void setSalary(double salary) {
			this.salary = salary;
		}


		@Override
		public String toString() {
			return "Employee [id=" + id + ", 名字=" + ename + ", 工资=" + salary + "]  ";
		}
		
		
		
	}

原因:

    我写的内部类是动态的,即public class开头无static关键字修饰,而测试主程序是静态的main方法。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,才可以再静态类中调用带类的成员变量和成员方法。
    为什么静态方法不能直接访问非静态成员呢?
    静态成员是在JVM的ClassLoader加载类的时候初始化的,而非静态成员是在创建对象,也就是new操作的时候才初始化的。类加载的时候初始化的静态成员已经分配内存空间,所以可以访问,而非静态成员还没有通过new创建对象而进行初始化,所有当然不能访问了。
   经过查证,是因为内部类是动态的(无static关键字修饰),而main方法是静态的,普通的内部类对象隐含地保存了一个引用,指向创建它的外围类对象,所以要在static方法(类加载时已经初始化)调用内部类的必须先创建外部类。

解决方案:

    1.将动态内部类改为静态(public static class)。
    2.即应该这样创建“DanymicTest test = new StaticCallDynamic().new DanymicTest();”其中StaticCallDynamic为外部类,DanymicTest为内部动态类;如果将内部内修改为静态类,可以在main中直接创建内部类实例。

    3.将内部类改为外部类。

    4.别用静态main方法调用。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值