Class inheritance and retrieval

first time i'm playing around with class inheritances etc but i'm a little confused with how I retrieve the information that I set. I've a class called ClientInfo, in that class there's just name and age. I have a class that extends this class called ClientAdditionalInfo, it just contains a string called 'additionalinfo'.

When I add my extended additional info to the link list, i can't retrieve it out, but I can still get the age and name. See below:

    List<ClientInfo> list = new LinkedList<>();       

    ClientAdditionalInfo additionalinfo = new ClientAdditionalInfo();
    additionalinfo.additionalinfo = "hi";
    additionalinfo.age = 4;
    additionalinfo.name = "name";

    list.add(additionalinfo);

    System.out.println(list.get(0).age);
    System.out.println(list.get(0).name);
    //System.out.println(list.get(0).additionalinfo);   how do i do this?

Now, I realise that I could change the class that the list holds to 'ClientAdditionalInfo', but then that would just feed into another question of what if I wanted to use more classes in this list like ClientLocation (i know I could put these vars in the ClientInfo) but i'm just trying to convey a point as I can see some situations where multiple extensions of a class might be needed in one list.

Sorry it's a pretty bad example and I realise I could have done it with animals or something to make it much clearer but I hope you can see my problem.

Thanks for your help. Ben

Jon Skeet
people
quotationmark

You would need to cast the result of list.get(0) - the compiler is complaining because List<ClientInfo>.get(...) will definitely return a reference to a ClientInfo-compatible object (or null), but it might not be a ClientAdditionalInfo:

ClientAdditionalInfo fetched = (ClientAdditionalInfo) list.get(0);
System.out.println(fetched.age);
System.out.println(fetched.name);
System.out.println(fetched.additionalinfo);

Note that you'll get a ClassCastException if the first element isn't a ClientAdditionalInfo. You can check that:

ClientInfo info = list.get(0);
if (info instanceof ClientAdditionalInfo)
{
    ClientAdditionalInfo fetched = (ClientAdditionalInfo) info;
    ...
}

This sort of thing is usually a design smell - typically if you need to know that elements of a collection are of a particular subclass (rather than just letting subclasses override methods from the superclass if they need to customize behaviour), then the collection type should be specified with that subclass. It's not always the case, but it's at least worth considering whether this should be a List<ClientAdditionalInfo>.

people

See more on this question at Stackoverflow