java 静态方法 实例化_java - 如何在静态方法中实例化非静态内部类

“常规”内部类具有指向外部类实例的隐藏(隐式)指针。 这允许编译器生成代码以便为您追逐指针而无需键入它。 例如,如果外部类中有变量“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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值