Reputation:
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?
Upvotes: 1
Views: 4185
Reputation: 2664
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();
Upvotes: 3