基底クラスの配列リスト内の子プロパティにアクセスします

Alvinoキャッチ:

私は、基本クラスの配列リスト内の子クラスのプロパティにアクセスしようとしています

ArrayList<Parent> listValue = new ArrayList<Parent>();
listValue.add(new Child1());
listValue.add(new Child2());

これは、クラスの親であります

class Parent{
String name;
public Parent(String name){
  this.name = name
  }
}

これは、子クラスであります

class Child extends Parent{
String childOnly;

public Child(String name){
super(name);
 }
}

そして、私はこのような何とかクラスのプロパティにアクセスしようとしています

string value = listValue.get(1).childOnly       
ペドロ・ボルヘス:
  1. あなたのリストは、このように、親の任意のサブクラスが含まれていることを指定します。
List<? extends Parent> listValue = new ArrayList<>();
  1. このように、リストからフェッチするときにオブジェクト出演:
if (listValue.get(1) instanceof Child)
{
    Child child = (Child) listValue.get(1);
    String value = child.childOnly;
}

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=395478&siteId=1