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.
You can use: –
To fetch the
membersusingenhanced-for loop, we used the concept of :-Super type Reference pointing the Subclass object. So, no matter whichsubclassobjects are stored in thelist, we always use asuper-classreference to point to them.. And thenTypeCastaccordingly by checking the actualinstance type..And make the return type of
getMembers()the same.. It would work.That way you can return
ListofMemberor any class thatextends your Memberclass.. And you don’t need to give the name of those class explicitly..