Java内部类

java内部类

内部类可以实现“java的多重继承”。

1..this.new

  • .this:如果要生成对于外部类的引用,可以使用外部类.this
  • .new:如果想要生成一个类的内部类的对象引用,使用new语法,格式为外部类对象.new 内部类()。如果是静态内部类,则不需要外部类的对象来生成。
class DotThis {
    public class Inner {
        public DotThis outer() {
            return DotThis.this;
        }
    }
}

class DotNew {
    public class Inner {}
    public static void main(String[] args) {
        DotNew dn = new DotNew();
        DotNew.Inner dni = dn.new Inner();
    }
}

2.外部类可以访问内部类的private属性

class Outter {
    private int i = 1;
    private int getI() {
        return i;
    }

    void f()
    {
        this.new Inner().fun();
    }
    class Inner {
        private int k = 23;
        void fun() {
            Outter.this.i = 2;
            int i = Outter.this.getI();
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        Outter outter = new Outter();
        outter.f();
        System.out.println(outter.new Inner().k);
    }
}

3.内部类的非常规用法

(1)定义在方法中的内部类

interface Destination {
    String readLabel();
}

class Outter {
    public Destination destination(String s) {
        class Inner implements Destination {
            private String label;
            private Inner(String whereTo) {
                label = whereTo;
            }
            public String readLabel() { return label; }
        }
        return new Inner(s);
    }
}

(2)匿名内部类

  • 下列的代码表示生成了一个继承(实现)于Contents的匿名内部类。
interface Contents {
    int value();
}

class Outter {
    public Contents contents() {
        return new Contents() { 
            private int i = 11;
            public int value() { return i; }
        }; 
    }
}

(3)嵌套类(静态内部类)

  • 要创建嵌套类,并不需要外部类的对象。
  • 不能通过嵌套类的对象访问其外部类的非静态对象。
  • 嵌套类能在内部包含static属性static方法以及static类
class A {
    private static class B {
        private static int a = 1;
        public static void fun() {}

        static class C {
            //...
        }
    }
}

4.内部类的继承

  • 内部类在构造时,其构造器必须连接到外部类的对象的引用。这个外部类引用必须要被初始化,而在类C中不存在默认的可连接的A对象。所以必须显式调用类A的构造。如下:
class A {
    class B {}
}

class C extends A.B {
    C(A a) {
        a.super();
    }
}

5.内部类的.class文件

  • 内部类编译后也会生成.class文件,class文件命名为外部类$内部类.class
  • 若是类的命名中包含$,这时生成的class文件名称是怎样的?
class AA$ {
    class AB$1 {}
    public static void main(String[] args) {
        
    }
}

其生成的class文件命名如下,可见并没有进行特殊处理。

posted @ 2021-01-07 17:35  光羽隹  阅读(97)  评论(0)    收藏  举报