No enclosing instance of type ObjectTest is accessible. Must qualify the allocation with an enclosin
刚刚写代码运行出错, 报的问题:
No enclosing instance of type ObjectTest is accessible. Must qualify the allocation with an enclosing instance of type ObjectTest (e.g. x.new A() where x is an instance of ObjectTest).
大概意思就是:无法访问ObjectTest类型的封闭实例。必须用ObjectTest(例如x)类型的封闭实例限定分配。new A()其中x是ObjectTest的实例)。
我要在mian方法里面调用自己写的内部类,出现了此问题。其实还是由于不仔细构成的,因为main方法是静态的,而自己写的内部类是动态的。只要在内部类前加上static就行。
问题出现在:
看代码:
package cn.liu.io3;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
public class ObjectTest {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream m = new ObjectOutputStream(bos);
//数据
m.writeUTF("你是谁");
m.writeInt(5);
//对象
m.writeObject("你是不是未来的你");
m.writeObject(new Date());
Employee temp = new Employee("马云",400);
m.writeObject(temp);
m.flush();
}
//javabean 用于封装数据
class Employee implements java.io.Serializable{
private String name;
private double salary;
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
}
只要修改class Employee implements java.io.Serializable为static class Employee implements java.io.Serializable即可。
也就是在内部类前加static
问题解决了,我们还要了解详情。上网看了看,这个帖子可以说明一些原理问题:
https://www.cnblogs.com/runnigwolf/p/5570810.html