内部クラスのインスタンスから外側のクラス属性にアクセスする
-
21-09-2019 - |
質問
次のコードが与えられます:
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");
//...
内側クラスの2つのインスタンスのnの値を比較できるように、擬似コードラインと何を交換できますか?
明らかな解決策を試してみる(n != that.n
)コンパイルしない:
Outer.java:10: cannot find symbol
symbol : variable n
location: class Outer.Inner
if (n != that.n) // pseudo-code line
解決
インスタンスのメソッドや変数と同様に、内部クラスはその囲まれたクラスのインスタンスに関連付けられており、そのオブジェクトのメソッドとフィールドに直接アクセスできます。 - Java Oo
内部クラスにゲッターメソッドを書くことができます。 n
外側のクラスの。
メソッドオン Inner
:
public int getOuterN() { return n; }
次に、この方法を使用して比較します。
getOuterN() != that.getOuterN()
所属していません StackOverflow