内部类中的方法可以访问父类的方法吗?
我不确定我的问题标题是否恰当地描述了我的情况,如果没有,我很抱歉!无论如何,假设我有以下代码片段(可见性如所述):
public class ChildClass extends ParentClass {
// more code
private void myMethod() {
MyClass mine = new MyClass() {
public void anotherMethod() {
// insert code to access a method in ParentClass
}
};
}
}
anotherMethod() 中的代码是否可以访问 ParentClass 中找到的受保护方法?如果是这样,该怎么办?
我尝试过类似的方法...
(ParentClass.this).parentMethod();
...但显然由于范围问题它不起作用。
I'm not sure if my question title describes my situation aptly, so my apologies if it doesn't! Anyway, let's say I have the following code snippet (visibility is as stated):
public class ChildClass extends ParentClass {
// more code
private void myMethod() {
MyClass mine = new MyClass() {
public void anotherMethod() {
// insert code to access a method in ParentClass
}
};
}
}
Is it possible for code within anotherMethod() to access a protected method found in ParentClass? If so, how can this be done?
I've tried something like...
(ParentClass.this).parentMethod();
...but obviously it doesn't work due to scope issues.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这编译得很好:
This compiles fine:
非静态内部类可以访问封闭类的所有方法,就好像它是它自己的方法一样:
静态内部类不能,因为静态内部类不绑定到父类的实例。这只能调用封闭类上的静态方法。
至于考虑继承的方法,非静态内部类中的方法可以使用封闭(外部)类的所有方法。
有趣的部分是
Test2.super.getOne()
,它确实从Test2.super
获取 getOne() ,这是一个Test
。这就像 Test2 访问该方法一样,即使用super
,尽管前缀为Test2
来指示您正在访问外部类的名称空间。A non-static inner class can access all methods of the enclosing class as if it were it's own methods:
A static inner class can not, as a static inner class is not bound to an instance of the parent class. That can only call static methods on the enclosing class.
As for methods when taking into account inheritance, an method in a non-static inner class can use all the methods of the enclosing (outer) class.
The interesting part is
Test2.super.getOne()
which indeed obtains getOne() fromTest2.super
, which is aTest
. This is just like Test2 would access the method, namely usingsuper
though prefixed withTest2
to indicate you're accessing the namespace of the outer class.Java 中无法访问“父类方法”,与可见性无关(子类的
parentMethod()
中的super.parentMethod()
除外)。也就是说,如果
ChildClass
重写parentMethod()
,则无法调用ParentClass.parentMethod()
(绕过ChildClass.parentMethod ()
) 来自ChildClass
的其他方法。但是,如果
ChildClass
不重写parentMethod()
,则该方法将由ChildClass
继承,以便您可以将其作为访问>ChildClass
的方法,即简单为parentMethod()
。There is no way to access "parent class method" in Java, irrelatively to visibility (except for
super.parentMethod()
in subclass'sparentMethod()
).That is, if
ChildClass
overridesparentMethod()
, there is no way to callParentClass.parentMethod()
(bypassingChildClass.parentMethod()
) from other methods ofChildClass
.However, if
ChildClass
doesn't overrideparentMethod()
, that method is inherited byChildClass
, so that you can access it as aChildClass
's method, i.e. simply asparentMethod()
.