1

I have a java program consisting of a class called Piece, has four children objects. Ie, Geometry, circle extends geometry, circle2 extends circle, etc.

I want to create an array of Geometry objects and access circle, or circle2 methods.

ex. Geometry[i].method1();

However, I cannot seem to do this. Is there a best practice for making an array of objects that have the same parent, and accessing methods of its child in this manner?

1 Answer 1

3

You can't call sub-class methods on parent-class objects. Think of it this way. A circle is a geometric shape. But not all geometric shapes are circles. So not all geometric shapes can have circle properties (and in this case methods).

What you have to do is tell the compiler to treat the Geometry object as a circle or any other sub-class Object under the parent-class Geometry. This is called "casting".

So basically you cast the Geometry object to a Circle object like this:

((Circle) Geometry[i]).method1();

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

5 Comments

Thanks. Just a quick question, an array of geometry objects would allow me to make children objects in it no problem right? Someone was telling me that the array size is allocated when its initiated, so there wouldnt be room for children objects that are different in size.
I do not quite get the question. But if you are asking is you can add any subclass of the Geometry class into the array then yes you can. However when you try to access it you will get back a Geometric object, not a circle. So if you wanna call some method of that object you have to know what type it is.
Now if you are talking about how many items you can store in the array. Then yes arrays have fixed size. so if you have 10 items in an array of size 10 and you want to store one more you have 2 options. 1) Copy the array into a bigger one. 2) Use an ArrayList
i mean more specifically, if the array is Geometry objects, and circle objects take more space in memory, does java just allocate enough for the children or is it changed in the memory when i assign a circle?
This is something beyond the scope of your question. Simply put, the size of each object stored in an array doesn't affect the functionallity of the array. The only size attribute that does, is the number of elements you want to store in it

Your Answer

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