2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数のクラスを保持するListを作る

Last updated at Posted at 2019-01-22

概要

スーパークラスのListを作って、実際にはサブクラスを保持しておきます。
abstractでサブクラス毎に別のデータを取得できます。

サンプル

AというAbstractクラスを親として、X,Yというサブクラスを作ります。

A.java
abstract class A {
    int a;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    abstract String hoge();
}
X.java
public class X extends A {
    String x;

    public String getX() {
        return x;
    }

    public void setX(String x) {
        this.x = x;
    }

    @Override
    String hoge() {
        return x;
    }
}
Y.java
public class Y extends A {
    String y;

    public String getY() {
        return y;
    }

    public void setY(String y) {
        this.y = y;
    }

    @Override
    String hoge() {
        return y;
    }
}

Aを要素としたArrayListに、X,Yそれぞれを追加します。

main.java
ArrayList<A> list=new ArrayList<>();
X x=new X();
x.setX("x!!");
Y y=new Y();
y.setY("y!!");
list.add(x);
list.add(y);

for(int i=0;i<list.size();i++){
    System.out.println(list.get(i).hoge());
}
->

I/System.out: 
x!!
y!!
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?