内部类(二)

1.4 嵌套类

不需要内部类对象与其外围类对象之间有联系,将内部类声明为static。这通常被称为嵌套类。

在一个普通的(非static)内部类中,通过一个特殊的this引用可以链接到其外围类对。而嵌套类没有这个特殊的this引用,这使它类似于一个static方法

  • 1)要创建嵌套类的对象,并不需要其外围类的对象。
  • 2)不能从嵌套类的对象中访问非静态的外围类对象。
interface Destination {
    String readLabel();
}

interface Contents {
    int value();
}

public class Parcel2 {
    
    private static class ParcelContents implements Contents {
        private int i = 11;
        @Override
        public int value() {
            return i;
        }
    }

    private static class ParcelDestination implements Destination {
        private String label;

        private ParcelDestination(String whereTo) {
            label = whereTo;
        }

        @Override
        public String readLabel() {
            return label;
        }

        public static void f() {}

        static int x = 10;

        static class AnotherLevel {
            public static void f() {}

            static int x = 10;
        }
    }
    
    public static Destination destination(String s){
        return new ParcelDestination(s);
    }
    
    public static Contents contents(){
        return new ParcelContents();
    }

    public static void main(String[] args) {
        Contents c = contents();
        Destination d = destination("China");
    }
}

1.4.1 接口内部的类

正常情况下,不能在接口内部放置任何代码,但嵌套类可以作为接口的一部分。放在接口中的任何类型都自动地是public和static地。所以我们可以将类名为为下例所示,甚至可以在内部类中实现其外围接口。

public interface ClassInInterface {
    void howdy();
    class Test implements ClassInInterface{
        @Override
        public void howdy() {
            System.out.println("Howdy!");
        }

        public static void main(String[] args) {
            new Test().howdy();
        }
    }
}

运行结果:

Howdy!

当我们想要创建某些公共代码,使得它们可以被某个接口的所有不同实现所共用,那么我们就可以使用接口内部的嵌套类。

1.4.2 从多层嵌套类中访问外部类的成员

一个内部类被嵌套多少层并不重要——它能透明地访问所有它所嵌入的外围类的所有成员。

class MNA {
    private void f() {
        System.out.println("f()");
    }

    class A {
        private void g() {
            System.out.println("g()");
        }

        public class B {
            void h() {
                System.out.println("h()");
                g();
                f();
            }
        }
    }
}

public class MultiNestingAccess {
    public static void main(String[] args) {
        MNA mna = new MNA();
        MNA.A mnna = mna.new A();
        MNA.A.B mnnab = mnna.new B();
        mnnab.h();
    }
}

运行结果:

h()
g()
f()

从例子中我们可以知到MNA.A.B中,调用方法g()和h()不需要任何条件(即使它们被定义为private)。

  • 内部类(一)https://www.jianshu.com/p/563a5c69a152
  • 内部类(二)https://www.jianshu.com/p/5b32ada40b0d

你可能感兴趣的:(内部类(二))