解释在Java中访问内部类的方法? [英] explain the way to access inner class in java?
问题描述
class Outer {
class Inner {
}
}
public class Demo {
public static void main(String args[]) {
Outer o = new Outer();
Outer.Inner inner = o.new Inner();
}
}
我为Inner
类对象创建引用的方式类似于访问Outer
类中的static
成员?
请您解释一下其背后的机制?
the way I create a reference for Inner
class object is something like accessing static
member in Outer
class ?
could you please explain the mechanism behind this ?
推荐答案
我为
Inner
类对象创建引用的方式类似于访问Outer
类中的static
成员
the way I create a reference for
Inner
class object is something like accessingstatic
member inOuter
class
完全没有-因为您正在使用Outer
的实例来访问Inner
的构造函数,所以这非常类似于访问Outer
类的 instance 成员. ,而不是其static
成员.声明中的Inner
类名称用其外部类Outer
的名称限定,以避免与顶级类的命名冲突.
Not at all - since you are using an instance of the Outer
to access the constructor of the Inner
, this is very much like accessing an instance member of the Outer
class, not its static
member. The name of the Inner
class in the declaration is qualified with the name of its outer class Outer
in order to avoid naming conflicts with top-level classes.
原因很容易理解:Inner
是一个非静态内部类,因此需要引用Outer
.它隐式地这样做,但是必须将引用传递给幕后的构造函数.因此,您可以在Outer
的实例上调用Inner
的构造函数.
The reason for that is easy to understand: Inner
is a non-static inner class, so it needs to reference an Outer
. It does so implicitly, but the reference must be passed to the constructor behind the scene. Therefore, you call a constructor of Inner
on an instance of Outer
.
制作static
类实例的语法与制作常规类实例的语法相似,不同的是嵌套类的名称必须以其外部类的名称作为前缀-即遵循static
语法:
The syntax for making instances of static
classes is similar to the syntax for making instances of regular classes, except the name of the nested class must be prefixed with the name of its outer class - i.e. following the static
syntax:
class Outer {
static class Inner {
}
}
public class Demo {
public static void main(String args[]) {
Outer.Inner inner = new Outer.Inner();
}
}
这篇关于解释在Java中访问内部类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!