2

Let's say I have a class called MemberNio (containing a SocketChannel and other nio specific objects) which extends Member class.

The method getMember(id) and getMembers return MemberNio objects. The layers of my application that don't need to know anything about the Nio stuff could just call the getMember method to get a member and use the supertype Member:

Member member = membersMgr.getMember(id);

But the problem occurs when I try to call getMembers:

List<Member> members =  membersMgr.getMembers(); // <- error, can't cast List<MemberNio> to List<Member>

That would force me to have MemberNio objects where I should only know about Member objects.

This is a recurring problem when I work with Lists and Interfaces/suptypes.

2
  • 1
    So why don't you return a list of Members from your method? Commented Sep 26, 2012 at 17:25
  • Well some classes need to MemberNio objects, otherwise I would only use Members. I could still create methods getMembersNio and another method getMembers, but it seems wrong to me. Commented Sep 26, 2012 at 17:29

2 Answers 2

6

You can use: -

List<? extends Member> members =  membersMgr.getMembers();
for (Member member: members) {
     if (member instanceof MemberNio) {
          MemberNio memNio = (MemberNio)member;
          /** Do your stuff **/
     }
} 

To fetch the members using enhanced-for loop, we used the concept of :- Super type Reference pointing the Subclass object. So, no matter which subclass objects are stored in the list, we always use a super-class reference to point to them.. And then TypeCast accordingly by checking the actual instance type..

And make the return type of getMembers() the same.. It would work.

That way you can return List of Member or any class that extends your Member class.. And you don't need to give the name of those class explicitly..

Sign up to request clarification or add additional context in comments.

1 Comment

But if I loop through the members objects of the list, how can I get a MemberNio object? List<? extends Member> members = membersMgr.getMembers(); for (MemberNio member : members) // <- error
1

Generics are invariant in nature. it means that List<MemberNio> is not subtype of List<Member> You can use wildcards to specify bounds.

 List<? extends Member> which means List of Member or any subclass of Member

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.