0

Class Structure

class Packet {}
class PacketList extends ArrayList<Packet> {} 

Now I am trying to cast object of ArrayList to Object of PacketList

List<Packet>  p = new ArrayList<Packet> ();
PacketList pList = p;

But it will not work. Please help me out

Error Message:

incompatible types: List cannot be converted to PacketList

1 Answer 1

1

PacketList extended the ArrayList<Packet>, which means newly introduced, or overriden methods that might require and depend on other artifacts only introduced in the new PacketList version. What if it refers to instance variables only available in PacketList? ArrayList won't have those instance variables, although you would intend to access them through those methods ...

No, you cannot assign an instance of a superclass, to a variable of the type matching an extending class.

You work the other way around, you use the super type as the generic type to assign extending (subclassed) instances.

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

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.