JAVA中关于主方法调用非静态方法的问题!

public class Rectangle {

private int height;
private int width;

public Rectangle(int height,int width ){
this.height = height;
this.width = width;

}

public int getsquare(){
return height*width;
}

public static void main(String[] args){
Rectangle square1 = new Rectangle(5,4);
System.out.print(square1.getsquare());//不是说主方法中不能调用非静态方法吗,为什么我这里调用了getsquare的非静态方法却可以运行呢?
}

}

你这里是通过对象square1调用的方法getsquare()
main函数里不能调用非静态方法是指不能通过this调用非静态方法,即
public static void main(String[] args){
getsquare(); //这里会出错
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-02-09
一个类中不能调用其他类中的非静态方法
相似回答