gpt4 book ai didi

java - 从内部类的实例访问外部类属性

转载 作者:搜寻专家 更新时间:2023-11-01 01:58:44 31 4
gpt4 key购买 nike

给定以下代码:

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

最佳答案

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. - Java OO

你可以在内部类中写一个getter方法,它返回外部类的n

Inner 上的方法:

public int getOuterN() { return n; }

然后用这个方法比较:

getOuterN() != that.getOuterN()

关于java - 从内部类的实例访问外部类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1776121/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com