Gerus
Gerus

Reputation: 61

Dart OOP - Not knowing exact class

I have three classes: apples, peaches and bananas. They all extend fruit. So I create them like:

Apple apple = Apple()

...

and then I would like to store them in a list.

List<Fruit> fruits = [apple, peach, banana]

Now I want to know the taste of the first list entry. So I might consider calling fruits[0].getTaste().

Do I get a correct answer here? Or does the list element not know that it has to call apples getTaste and calls the one of Fruit which can't answer correctly of course. So is the list element an apple or a fruit?

I hope it is clear what I mean. And if so, is there a typical way of solving problems like this?

Thank you very much.

Upvotes: 0

Views: 37

Answers (1)

lrn
lrn

Reputation: 71623

Yes, you get the correct result here.

Dart instance methods are virtual, which means that the version invoked depends on the run-time type of the receiving objects, not the static type. In this case, you are calling the Apple.getTaste methods.

Upvotes: 1

Related Questions