public class TryVariableArgumentList{
public static void main(String[] args){
printAll(2, "two" , "four", 5.0,"four point five");
printAll();
printAll(26,"Anything",true,4E6,false);
}

public static void printAll(Object ... args){
for(Object arg : args){
System.out.print(" " + arg);
}
System.out.println();
}
}
   如果删除printAll方法定义前的static关键字后,编译器报错提示:non-static method printAll(java.lang.Object...)can't be referenced from s static context.
   请问,这里的static context是指实参吗,为什么静态方法不能这么处理呢?谢谢大家的解答。

解决方案 »

  1.   

    main 方法是 static 的,所以其调用的方法也必须是 static 的,也就是类一级的才行
    当然,不使用类一级的也可以,不过得先创建实例public class TryVariableArgumentList{
        public static void main(String[] args){
            TryVariableArgumentList o = new TryVariableArgumentList();
            o.printAll(2, "two" , "four", 5.0,"four point five");
            o.printAll();
            o.printAll(26,"Anything",true,4E6,false);
        }
        
        public void printAll(Object ... args){
            for(Object arg : args){
                System.out.print(" " + arg);
            }
            System.out.println();
        }
    }
      

  2.   

    非常感谢java2000_net的回答,谢谢。
    我还有些对“类一级”的概念不是很懂,是指什么意思啊?
      

  3.   

    类一级 = 调用时,不需要类的实例
    比如
    TryVariableArgumentList.putAll(); // 就是直接调用 TryVariableArgumentList 的类一级的(静态)方法

    new TryVariableArgumentList().putAll2(); // 就是先生成TryVariableArgumentList的对象实例,在调用此对象实例的方法比如:
    public class TryVariableArgumentList {
      // 此方法必须先创建对象的实例才能访问
      public String hello(){
        return "Hello world! ";
      }
      // 此方法可以直接访问,也就是可以在 main里面直接调用
      public static String helloGloble(){
        return "Hello Globle!";
      }  public static void main(String[] args){
        TryVariableArgumentList.helloGloble();
        new TryVariableArgumentList().hello();
      }  
    }