内部类
- 内部类共分为4种:
静态内部类(static inner class):只能访问外部类的静态成员变量与静态方法,生成静态内部类对象的方式为:OuterClass.InnerClass inner = new uterClass.InnerClass()
1234567891011121314151617181920class StaticInner {private static int a = 4;public static class Inner{public void test() {System.out.println(a);}}}class StaticInnerTest {public static void main(String[] args) {StaticInner.Inner inner = new StaticInner.Inner();inner.test();}}成员内部类(menber inner class):可以访问外部类的静态与非静态的方法与成员变量。生成成员内部类对象的方式为:MemberInner.Inner2 inner2 = new MemberInner().new Inner2();
若想在局部内部类中访问外部类成员变量,语法为:
OuterClass.this.a;1234567891011121314151617181920class MemberInner {private int a = 4;public class Inner2{private int a = 5;public void doSomething() {//访问外部类属性System.out.println(MemberInner.this.a);}}}class MemberInnerTest {public static void main(String[] args) {MemberInner.Inner2 inner2 = new MemberInner().new Inner2();inner2.doSomething();}局部内部类(Local Inner Class):定义在方法当中,只能访问方法中声明的final类型的变量。
12345678910111213141516171819202122232425262728public class LocalInnerClass {public void doSomething() {final int b = 4;class Inner3 {public void test() {System.out.println(b);}}new Inner3().test();}}class LocalInnerClassTest {public static void main(String[] args) {LocalInnerClass localInnerClass = new LocalInnerClass();localInnerClass.doSomething();}}匿名内部类(g):匿名内部类会隐式地集成一个父类或实现一个接口。
123456789101112131415161718192021222324252627public class AnonymousInnerClass {@SuppressWarnings(value = "deprecation")public String get(Date date) {return date.toLocaleString();}public static void main(String[] args) {AnonymousInnerClass anonymousInnerClass = new AnonymousInnerClass();// String str = anonymousInnerClass.get(new Date());// System.out.println(str);//匿名内部类继承了date类String str = anonymousInnerClass.get(new Date(){@Overridepublic String toLocaleString() {return "hello world";}});System.out.println(str);}}