[JAVA] Create a List that holds multiple classes

Overview

Create a list of superclasses and actually hold subclasses. You can get different data for each subclass with abstract.

sample

Create subclasses X, Y with the Abstract class ʻA` as the parent.

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;
    }
}

Add X and Y to ʻArrayList with ʻA as an element.

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!!

Recommended Posts

Create a List that holds multiple classes
How to create a class that inherits class information
Create Scala Seq from Java, make Scala Seq a Java List
Create a docker image that runs a simple Java app
[SwiftUI] Create a TextField that looks like a Qiita tag
Get a list of classes in a Guava specific package
[Rails] Volume that displays favorites and a list of favorites
[Java] Create a filter
List and happy classes
Create a page control that can be used with RecyclerView
Create a jar file that can be executed in Gradle
Determine that the value is a multiple of 〇 in Ruby
A program that counts the number of words in a List