0

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.

2 Answers 2

3

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.

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

1 Comment

See Liskov Substitution Principle: A Uav is a Airplane.
0

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

2 Comments

I'm really sorry for this! I meant to say UAV is its own parent class. How would i approach the situation then? I'm really grateful for the help:)
It doesn't matter.If we want distinguish Airplane and Uav from Object , we can try judge like this before invoke getPrice() method: if(flying_Array[0] instance of Airplane){ (Airplane(flying_Array[0] )).getPrice();}. the "instanceof" is a reserved word of java ,means if the instance left is the type of class right (or inherit the class right).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.