2011-05-05 71 views
1

我的代码:静态内部类 - 怪异

public class MyTest { 
    public class StringSorter implements Comparator<String> 
    { 
     public StringSorter() {} 

     public int compare(String s1, String s2) 
     { 
      int l1 = s1.length(); 
      int l2 = s2.length(); 
      return l1-l2; 
     } 
    } 

    public static void main(String[] args) { 
     System.out.println("Hello, world!"); 

     StringSorter sorter = new StringSorter(); 
     Set<String> sets = new TreeSet<String>(sorter); 
     sets.add(new String("he")); 
     sets.add(new String("hel")); 
     sets.add(new String("he")); 
     sets.add(new String("hello")); 

     for (String s: sets) 
     { 
      System.out.println(s); 
     } 
    } 
} 

它会抱怨错误: “MyTest.java:41:非静态变量这不能从静态上下文中引用”

删除这一行将通过编译。但是,我们需要在'static main'方法中使用许多String对象。 String和StringSorter有什么区别?

如果我将StringSorter更改为静态内部类,它将被编译成OK。静态内部类如何修复编译错误?

+1

你应该只用“他”而不是新的String(“他”) – 2011-05-05 10:08:02

+0

为什么^^谢谢你的提醒? 。 – pengguang001 2011-05-05 10:16:22

回答

2

StringSorter是一个内部类,并且总是“绑定”到外部类MyTest的实例(它可以访问它的成员,调用它的方法等)。由于您尝试从静态上下文(静态主要方法)实例化它,因此失败。相反,您可以使内部类为静态(如static public class StringSorter)使其工作。

或者,您可以在MyTest之外移动StringSorter,在这种情况下,它们是单独的类。 (如果您想要将这两个类仍保留在同一个文件中,则必须删除public修饰符,因为每个源文件只允许一个公共类(带有该文件的名称)。

另一种方法是从主方法将你的“测试代码”到MyTest(因此非静态上下文)的一些成员方法和调用此方法...

+0

我不明白你最后的提议。 MyTest的非静态方法无法从静态主方法中调用。 – Agemen 2011-05-05 10:22:13

+0

我的意思是什么:摆脱'main'所有代码的一些方法'测试()''中MyTest',谱写'MyTest.main':'新MyTest的()测试()'... – dcn 2011-05-05 10:23:37

+0

确定。 ,我不清楚。这样,你可以实例化一个Mytest对象,然后调用instanciate嵌套类。 – Agemen 2011-05-05 10:32:52

0

正如DCN说,你有到static关键字添加到StringComparator(见下文):

public static class StringSorter implements Comparator<String> 

内部类通常静态,因为它们通常是工具类(在你的情况是相同的; StringComparator可帮助您根据长度比较字符串)。

0

This tutorial很好地解释了如何处理内部类。在你的代码中,你试图从你的主要方法中使用MyTest.StringSorterMyTest.main是静态的,所以它不能访问在其外部定义的非静态字段,方法,内部类。

当使StringSorter为静态时,可以从外部类的静态方法调用此内部类。

当你打电话给你的原代码,你不的MyTest实例工作。您正在使用其静态方法之一。它是在教程中说:

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

希望它更清晰现在;-)