Create a list of superclasses and actually hold subclasses. You can get different data for each subclass with abstract.
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