Skip to content
Advertisement

Create a list with only base class elements

In Java I have a class

JavaScript

and subclass

JavaScript

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:

JavaScript

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:

JavaScript

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:

JavaScript

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:

JavaScript

It sounds like you’re slightly confused about subclassing.

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