Created
August 6, 2012 02:06
-
-
Save pooooch/3269106 to your computer and use it in GitHub Desktop.
about innerClass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
public class OuterClass { | |
private static int x = 0; | |
private int y = 0; | |
//非static内部类 | |
class InnerClass { | |
//可以直接访问OuterClass的private field,包括static,非static | |
public void change() { | |
x++; | |
y++; | |
} | |
//不可以声明static方法 | |
// public static void staticChange() { | |
// | |
// } | |
} | |
//static内部类 | |
static class StaticInnerClass { | |
public void change() { | |
x++; | |
// y++;//不可访问非 static field | |
} | |
public static void staticChange() { | |
x++; | |
// y++;//不可访问非static field | |
} | |
} | |
public static void main(String[] args) { | |
OuterClass oc = new OuterClass(); | |
//访问非static内部类的非static方法 | |
oc.new InnerClass().change(); | |
//访问static内部类的非static方法 | |
new OuterClass.StaticInnerClass().change(); | |
//访问static内部类的static方法 | |
OuterClass.StaticInnerClass.staticChange(); | |
System.out.println(OuterClass.x); | |
System.out.println(oc.y); | |
//另外,内部类还可以写在外部类的方法中,在这种情况下 | |
//只可以定义非static内部类,不可以定义static内部类,定义的内部类中不可以定义static方法 | |
//外部类的方法如果是static的,则不可以访问外部类的非static field | |
//匿名内部类 | |
Collections.sort(new ArrayList<Integer>(), new Comparator<Integer>() { | |
@Override | |
public int compare(Integer o1, Integer o2) { | |
if (o1 == null) { | |
if (o2 != null) { | |
return 1; | |
} else { | |
return 0; | |
} | |
} else if (o2 == null) { | |
return -1; | |
} else { | |
return o1 - o2; | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment