Skip to content
Advertisement

Create a list with only base class elements

In Java I have a class

Foo {
    String a;
}

and subclass

Bar extends Foo {
    String b;
}

Now let’s say I have List<Bar> bars.

How can I create from this a List of Foo (and I only want the a field to appear, not b)

Advertisement

Answer

What you want is impossible; let’s say you have your bars list which contains 5 Bar instances.

It is not possible in java to convert Bar instances to Foo instances; nothing in the language lets you do this. You can of course program it (e.g. that Foo has this cloning constructor:

class Foo {
  String a;

  public Foo(Foo toClone) {
    this.a = toClone.a;
  }
}

But the point is: You’d have to write that, the language will not do it for you.

The way subclassing works: All Bars are also Foos. So, you can do this:

Bar b = new Bar(...);
Foo clone = new Foo(b);

Which will ‘work’ – ‘b’ is of type Bar which is fine when invoking a method or constructor that wants a Foo, as Bar is a subtype of Foo.

If you want to treat your list as Foos instead, feel free:

List<Bar> bars = List.of(bar1, bar2, bar3);
List<? extends Foo> foos = bars;

And foos.get(0) will be an expression of type Foo (not Bar), and thus java won’t let you call things on whatever foos.get(0) returns that only Bar has. However, make no mistake, foos.get(0) still returns a Bar instance:

Foo f = foos.get(0);
System.out.println(f.getClass()); // prints 'Bar'
System.out.println(f instanceof Bar); // Returns 'true'

It sounds like you’re slightly confused about subclassing.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement