无法从静态上下文中引用。我这个代码应该怎么改?

卖牙膏的芖口钉 2012-03-01 08:24:49
class Box{
int length; //length width height
int width;
int height;

void setInfo(int l,int w,int h){
length=l;
width=w;
height=h;
}
int volume(){ //体积
return length*width*height;
}
int area(){ //表面积
return (length*width+width*height+length*height)*2;
}
public String toString(){
return "长:"+length+"\n"+"宽:"+width+"\n"+"高:"+height+"\n"+"体积:"+volume()+"\n"+"表面积:"+area();
}
void showInfo(){
System.out.println(toString()+"\n");
}
}
public class BoxTest{
public static void main (String [] args){
Box len=new Box();
Box wid=new Box();
Box hei=new Box();

Box.setInfo(123,321,213);

Box.showInfo();
}
}

编译后显示:
Boxtest.java:30:错误:无法从静态上下文中引用非静态 方法 setInfo(int,int,int)
Box.setInfo(123,321,213);
Boxtest.java:32:错误:无法从静态上下文中引用非静态 方法 showInfo()
Box.showInfo();
2个错误
...全文
110 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
原来我创建了三个对象,只用创建一个就好了!
ncist_jianeng 2012-03-01
  • 打赏
  • 举报
回复
把setInfo和showInfo方法都加上static修饰符,
  • 打赏
  • 举报
回复
还是解决不了呃!错误更多了!!

[Quote=引用 3 楼 michael529 的回复:]

你的 setInfo和showInfo方法都不是静态的,而main方法是静态的,静态方法只能调用静态方法。
解决方法一:把setInfo和showInfo方法都加上static修饰符,
解决方法二:用new Box.setInfo()的形式调用。
[/Quote]
  • 打赏
  • 举报
回复
我试试!!!
[Quote=引用 3 楼 michael529 的回复:]

你的 setInfo和showInfo方法都不是静态的,而main方法是静态的,静态方法只能调用静态方法。
解决方法一:把setInfo和showInfo方法都加上static修饰符,
解决方法二:用new Box.setInfo()的形式调用。
[/Quote]
  • 打赏
  • 举报
回复
还是不行呃!!
jasonlee529 2012-03-01
  • 打赏
  • 举报
回复
你的 setInfo和showInfo方法都不是静态的,而main方法是静态的,静态方法只能调用静态方法。
解决方法一:把setInfo和showInfo方法都加上static修饰符,
解决方法二:用new Box.setInfo()的形式调用。
你佛 2012-03-01
  • 打赏
  • 举报
回复
可以在你的setInfo(int,int,int)和setInfo()方法前加static关键字, 或者你在BoxTest类中用具体对象的引用去调用这两个方法都行。
噢噢噢噢 2012-03-01
  • 打赏
  • 举报
回复

public static void setInfo()

51,408

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧