JAVA高手们来帮帮我这个小菜鸟吧~~~~

来源:百度知道 编辑:UC知道 时间:2024/05/31 12:56:50
错误提示: 无法从静态上下文中引用非静态 变量 this
LeastNumb MinNumber = new LeastNumb();
代码段:
public class App2_8
{
public static void main(String args[])
{
int a[] = {8,3,7,88,9,23};
LeastNumb MinNumber = new LeastNumb();
MinNumber.least(a);
}
}
class LeastNumb
{
public static void least(int array[])
{
int temp = array[0];
for(int i=0 ; i<array.length ; i++)
if(temp>array[i])
temp = array[i];
System.out.println("minnumber=" + temp);
}
}

不是吧,哥们,我怎么可以运行,得到正确结果,不过你这样访问静态方法是有个警告的,最好改成类引用,就是把MinNumber.least(a)改成LeastNumb.least(a),就OK了。

LeastNumb MinNumber = new LeastNumb();
MinNumber.least(a);
改成LeastNumb.least(a);

静态方法不用实例化,直接通过类名.方法名来调用

因为public static void least(int array[])方法是静态的,可以直接用LeastNumb.least(a)来调用,不用new对象的。

静态类名.方法名
就可以引用了。。
如果你还new的话,为什么还要写成静态的呢?