从内部类的实例访问外部类属性
给出以下代码:
public class Outer
{
public final int n;
public class Inner implements Comparable<Inner>
{
public int compareTo(Inner that) throws ClassCastException
{
if (Outer.this.n != Outer.that.n) // pseudo-code line
{
throw new ClassCastException("Only Inners with the same value of n are comparable");
//...
我可以用伪代码行交换什么,以便可以比较内部类的两个实例的 n 值?
尝试明显的解决方案 (n != that.n
) 无法编译:
Outer.java:10: cannot find symbol
symbol : variable n
location: class Outer.Inner
if (n != that.n) // pseudo-code line
Given the following code:
public class Outer
{
public final int n;
public class Inner implements Comparable<Inner>
{
public int compareTo(Inner that) throws ClassCastException
{
if (Outer.this.n != Outer.that.n) // pseudo-code line
{
throw new ClassCastException("Only Inners with the same value of n are comparable");
//...
What can I swap out with my pseudo-code line so that I can compare the values of n for the two instances of the Inner class?
Trying the obvious solution (n != that.n
) doesn't compile:
Outer.java:10: cannot find symbol
symbol : variable n
location: class Outer.Inner
if (n != that.n) // pseudo-code line
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以在内部类,返回外部类的
n
。Inner
上的方法:然后使用此方法进行比较:
You could write a getter method in the inner class, which returns
n
of the outer class.Method on
Inner
:Then compare using this method: