4

So I have this one line of code here:

LinkedList<Integer> p = (LinkedList) obj.c.clone(); 

I was wondering why do you need the (LinkedList) part before obj.c.clone()?

4 Answers 4

3

The answer is: You need type casting to get access to target class methods and fields.

Object and LinkedList is same type hierarchy, so you can cast, otherwise You would get ClassCastException in Java. For more information about type casting, See this link.

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

Comments

3

Method Object.clone() returns result of Object type. If you want use it as LinkedList you need explicit cast result to LinkedList type.

Comments

2

clone() method returns an Object, so you have to cast it to LinkedList

Comments

2

LinkedList class implements Java´s clonable interface. If you read the documentation on that concrete interface you find clone deffinition is:

protected Object clone() 

That is, a reference to an Object object, in Java, to any object which is not an unwrapped basic type.

You need to cast the reference type to LinkedList´s in order to be able to use ("view") its methods/attributes not included in Object class definition.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.