关于“无法从静态上下文中引用非静态 变量 this”
01:15:21
摘自zhidao.baidu.com
public class fengzhuang { public static void main(String []args) { Clerk clerk1=new Clerk("职员一",25,2012.12f); System.out.println("Name:"+clerk1.name+" Age:"+clerk1.age+" Salary:"+clerk1.salary); //试试能不能直接访问private System.out.println("Name:"+clerk1.name+" Age:"+clerk1.age+" Salary:"+clerk1.getSalary()); //再正儿八经调用public方法访问 } class Clerk { public String name; public int age; private float salary; public Clerk(String name,int age,float sal) { this.name=name; this.age=age; this.salary=sal; } public float getSalary() { return this.salary; } } }
程序报错
问题在于你把 class Clerk 放到了 public class fengzhuang 内部
Clerk 成了fengzhuang 的非静态内部类,属于fengzhuang 的一个成员
在静态方法main中不能访问非静态的成员,也就不能直接new Clerk()
只能通过外部类的对象访问。
把Clerk clerk1=new Clerk("职员一",25,2012.12f);改成:
Test.Clerk clerk1=new Test().new Clerk("职员一",25,2012.12f);
或者把class Clerk放到fengzhuang 类外面就好了。