内部类共有四种
1.static inner class静态内部类.<该类属于类本身的StaticInner.Innerinner = new StaticInner.Inner();>
a.只能够访所在类的静态的成员变量或方法
packagecom.cb.innerclass;
public class StaticInnerClass {
public static void main(String[] args) {
StaticInner.Inner inner = new StaticInner.Inner();
inner.test();
}
}
class StaticInner {
private static int a = 4;
private int b=5;
public static class Inner {
public void test() {
System.out.println(a);
// System.out.println(b);不能访问
}
}
}
2.Member inner class 成员内部类 (没有用static来修饰)<该类属于类的对象MemberInner.Innerinner = (new MemberInner()).new Inner();>
a.可以访问一切所在类的成员和方法
package com.cb.innerclass;
class MemberInner {
private int a = 4;
public class Inner {
private int a=5;
public void doSomething() {
System.out.println(MemberInner.this.a);
}
}
}
public class MemberInnerClass {
public static void main(String[] args) {
MemberInner.Inner inner = (new MemberInner()).new Inner();// 实例化
inner.doSomething();
}
}
3.LocalInner Class 局部内部类
定义在方法中,只能访问所在内中被final修饰的类型变量
class LocalInner {
publicfinal int b=3;
public voiddosomething() {
final inta=4;
class Inner{
public voidtest() {
System.out.println("HelloWorld!!!");
System.out.println(a+b);
}
}
newInner().test();
}
}
publicclass LocalInnerClassTest {
publicstatic void main(String[] args) {
LocalInnerlocalInner = new LocalInner();
localInner.dosomething();
}
}
4.匿名内部类(AnonymousInner Class)会隐式的继承一个父类或者接口
packagecom.cb.innerclass;
importjava.util.Date;
publicclass AnonymousInnerClassTest {
publicString gert(Date date) {
returndate.toLocaleString();
}
publicstatic void main(String args[]) {
AnonymousInnerClassTesttest = new AnonymousInnerClassTest();
// Stringstr=test.gert(new Date());
//System.out.println(str);
String str= test.gert(new Date() {// 生成了一个继承了Date类的一个子类的对象
publicString toLocaleString() {
return "Hello World!!!";
}
});
System.out.println(str);
}
}