2016-07-30 5 views
-4
class Parent 
{ //need to access variable of child class 
} 

class Child extends Parent 
{ int a=10; 
} 
+3

no。これは多くの反省と一般的に悪い考えがなければ不可能です。 – Dallen

+1

親は子クラスの依存関係や知識を決して持つべきではありません。期間。 –

+5

これはあなたのデザインが間違っていることを明確に示しています。 – bradimus

答えて

0

リフレクションを使用して、デザインや発見を通して、子供について何かを知る必要があります。

この例は、「パッケージ」または「パブリック」であり、「プライベート」ではない「a」に依存します。

public int getChildA() { 
    int a = 0; 
    if (this instanceof Child) { 
     a = ((Child)this).a; 
    } 
    return a; 
} 
0

本当に必要な場合は、反射でフィールドを取得し、フィールドが見つからない可能性をキャッチしてください。しかし、これはまだ将来の設計から、本当に悪い考えです、

static class Parent 
{ 
    public int getChildA(){ 
     try { 
      Class clazz = Child.class; 
      Field f = clazz.getDeclaredField("a"); 
      if(!f.isAccessible()) 
       f.setAccessible(true); 
      return f.getInt(this); 
     } catch (NoSuchFieldException ex) { 
      //the parent is not an instance of the child 
     } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) { 
      Logger.getLogger(SOtests.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     return -1; 
    } 
} 

static class Child extends Parent 
{ 
    int a=10; 
} 

public static void main(String[] args) { 
    Child c = new Child(); 
    Parent p = (Parent) c; 
    System.out.println(p.getChildA()); 
} 

出力は10次のとおりです。のようなものを試してみてください。私もデモのクラスを作る必要がありましたが、問題なく戻すことができます。

関連する問題