PayrollPaul
PayrollPaul

Reputation: 87

Calling method from an array of type Object

EDIT oh my god I meant to say that UAV is another Parent class

I have various classes some are parent and the others are children example

Parent Class Airplane 
Child  Class Helicopter
Parent  Class Uav

The Airplane class has a accessor method called getPrice() which simply returns the instance variable price.

The problem arises when I get an array of objects that hold all these different types so for example

Airplane aObj=new Airplane();

Helicopter hObj=new Helicopter();

Uav uObj=new Uav();

Object flying_Array[]=new Object[4];

flying_Array[0]=aObj;

flying_Array[1]=hObj;

flying_Array[2]=uObj;

Now when I try to do flying_Array[0].getPrice();

// eclipses gives me an error and my method doesn't show up in the proposals.

//This is my first post so I'm sorry in advance if my formatting is weird.

Upvotes: 0

Views: 129

Answers (2)

FollowF
FollowF

Reputation: 21

1.theory

You should understand polymorphism of java first. Under the character ,we can assign child class instance to parent class type variable .But we should notice that the variable's type is parent class , so it can only invoke the methods in the parent class.

2.in your case

The array type is Object , it means the variable type is Object ,so we can assign Airplane instance and its childrens to the array element.However,when we want to invoke the mothod via the variable (type Object),we can only invoke the method in Object.

3.solution:

Just use Airplane take the place of the type of array,in this polymorphism ,parent class is Airplane ,it has the method of getPrice().

Airplane aObj=new Airplane();

Helicopter hObj=new Helicopter();

Uav uObj=new Uav();

Airplane flying_Array[]=new Airplane[4];

flying_Array[0]=aObj;

flying_Array[1]=hObj;

flying_Array[2]=uObj;

:D

Upvotes: 0

Peeyush
Peeyush

Reputation: 432

Object doesn't have getPrice method defined, but Airplane does. You should create an array of Airplane type.

Airplane flying_Array[]=new Airplane[4];

Since Helicopter and Uav class extends Airplane class, you can assign an instance of Helicopter or Uav to variable which is of Airplane type.

Upvotes: 3

Related Questions