“常规”内部类具有指向外部类实例的隐藏(隐式)指针。这使编译器可以生成代码来为您寻找指针,而无需键入它。例如,如果外部类中有一个变量“ a”,那么内部类中的代码只能执行“ a = 0”,但是编译器将为“ outerPointer.a = 0”生成代码,并在其中保留隐藏指针封面。

这意味着在创建内部类的实例时,必须具有外部类的实例才能将其链接到。如果在外部类的方法中进行此创建,则编译器会知道将“ this”用作隐式指针。如果要链接到其他外部实例,则可以使用特殊的“新”语法(请参见下面的代码段)。

如果将内部类设置为“静态”,则没有隐藏的指针,并且内部类无法引用外部类的成员。静态内部类与常规类相同,但是其名称的作用域位于父类内部。

这是一段代码,演示了创建静态和非静态内部类的语法:

public class MyClass {

int a,b,c; // Some members for MyClass

static class InnerOne {

int s,e,p;

void clearA() {

//a = 0;  Can’t do this … no outer pointer

}

}

class InnerTwo {

//MyClass parentPointer;      Hidden pointer to outer instance

void clearA() {

a = 0;

//outerPointer.a = 0      The compiler generates this code

}

}

void myClassMember() {

// The compiler knows that “this” is the outer reference to give

// to the new “two” instance.

InnerTwo two = new InnerTwo(); //same as this.new InnerTwo()

}

public static void main(String args[]) {

MyClass outer = new MyClass();

InnerTwo x = outer.new InnerTwo(); // Have to set the hidden pointer

InnerOne y = new InnerOne(); // a “static” inner has no hidden pointer

InnerOne z = new MyClass.InnerOne(); // In other classes you have to spell out the scope

}

}


版权声明:本文为weixin_35167817原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_35167817/article/details/114076385