michael16574
michael16574

Reputation: 71

Java Child referenced type inside Parent array

For the following question,

Suppose the object referenced in a cell of

ArrayList<Polygon> pentagonGroup

is of type Pentagon. If you later reference that object, what type will it have?

What would the answer be?

I tried playing around in a IDE and it seems like child objects even when placed into a Parent list are identified as a Child when doing the following operation.

Child c = new Child();
ArrayList<Parent> pa = new ArrayList<Parent>();
pa.add(c);
Class cls = pa.get(0).getClass();
System.out.println(cls.getName());

This seems kind of odd when one is unable to use Child object specific methods without downcasting it back to an Child.

System.out.println(pa.get(0).getChildMessage()); // invalid
System.out.println(((Child)pa.get(0)).getChildMessage()); // valid

Given my results the answer to the first question would be (Pentagon). Would that be correct?

EDIT:

So I'm actually still not sure about the very first question asked above; Would the answer be Polygon or would it be Pentagon?

Upvotes: 0

Views: 373

Answers (2)

Alan
Alan

Reputation: 31

Assuming Child extends Parent, the ArrayList is composed of Parent objects, as far as the compiler is concerned. So when you get a value from the list, it is a Parent. In your case, it is also a Child, but it might not be in the general case.

Remember java is not like groovy with dynamic binding, so if the Parent doesn't have the getChildMessage() method, it has no method it can assign to. So you have the option of either defining a getChildMessage() method in Parent (maybe return an empty string or throw an exception) and override it in Child, or downcasting as you did, but then make sure it is a Child first with instanceof, e.g.

Upvotes: 0

xingbin
xingbin

Reputation: 28279

At runtime, you can get the type of pa.get(0):

Class cls = pa.get(0).getClass();
System.out.println(cls.getName());

While at compile stage, the compiler only knows pa.get(0) is Parent, so you can not call pa.get(0).getChildMessage() without down casting. It's for type safe.

In fact, you can casting any object to Child to make it compile,

Object o = new Object();
System.out.println(o.getChildMessage());

but it will throw casting exeception at run time.

Upvotes: 2

Related Questions