This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                7年前关闭。
            
        

//这是一个小代码,用于研究集合的工作原理,但是当我在main方法中创建Mountain对象时,会出现错误。最后进一步解释。

import java. util. * ;
    public class sortMountains {
     class Mountain {
               String name;
               int height;
               Mountain(String n, int h) {
                 name      = n;

                 height = h;
               }
               public String toString( ) {
                 return name +  + height;
               }
            }
    List<Mountain> mtn  = new ArrayList<Mountain> ();
      class NameCompare implements Comparator <Mountain> {
        public int compare(Mountain one, Mountain two) {
          return one.name. compareTo(two. name);
      }
      }
      class HeightCompare implements Comparator <Mountain> {
        public int compare(Mountain one, Mountain two) {
    return (two. height - one. height) ;
    }

      }
      public void go() {
            mtn.add(new Mountain("Longs ", 14255));
            mtn.add(new Mountain("Elbert ", 14433));
            mtn.add(new Mountain("Maroon " , 14156));
            mtn.add(new Mountain("Castle ", 14265));

            System.out.println("as entered:\n" + mtn);
            NameCompare nc = new NameCompare();
            Collections.sort(mtn, nc);
            System.out.println("by name:\n'" + mtn);
            HeightCompare hc = new HeightCompare();
            Collections.sort(mtn, hc);
            System.out.println("by height:\n " + mtn);
          }
    public static void main(String args[]){

        sortMountains   sorting=new sortMountains();
        sorting.go();
         //error line   Mountain a=new Mountain("Everest",12121);
    }

    }


上面的代码在没有错误的情况下编译正常,但是当我想在main方法中创建Mountain对象时,出现错误“无法从静态方法引用非静态”

最佳答案

使Mountainstatic如下所示:

static class Mountain {
   ...


如果不这样做,则每个Mountain实例都必须具有一个与之关联的sortMountains实例。由于main()中没有这样的实例(方法本身是static),因此编译器不允许您在其中实例化Mountain

有关更多讨论,请参见:


Java: Static vs non static inner class
Java inner class and static nested class

关于java - 不允许在main方法中声明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13507952/

10-11 05:12