无法从静态上下文引用非静态变量this

来源:百度知道 编辑:UC知道 时间:2024/09/19 16:21:29
public class ppf {

/**
* @param args the command line arguments
*/
public interface caMath
{
int calength();
void setX(int x);
void setY(int y);
}
public class Math implements caMath
{
private int x,y;
Math()
{
x=1;y=1;
}
Math(int x1,int y1)
{
x=x1;
y=y1;
}
public void setX(int x1)
{
x=x1;
}
public void setY(int y1)
{
y=y1;
}
public int calength()
{
return x+y;
}
}
public static void main(String[] args)
{
caMath tmp = new Math(); <--------错误指向这里
}

}
如果不把这个类写在主类里就没问题,但是就不能加public了,但是书上都写了public啊

public static void main(String[] args)
{
ppf p = new ppf();
caMath tmp = p.new Math();
}

因为Math是内部类,所以要先定义一个ppf的实例,然后用内部类的定义方式来定义Math。