this is from Java Core Level 3 Lesson 2, Beer part 2 Recovery.
really want to know why this is allowed in Line 10 --> Drink beer = new AlcoholicBeer(); Drink is an interface, but here it's used as a Reference type. How is this possible? Someone did ask this question, but I could not understand the explanation (really tried). If someone could explain this well, I'd appreciate it.
why is this allowed?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Gellert Varga
28 May 2021, 01:10
With some inaccuracy, you could say that AlcoholicBeer is a descendant (child) of the Drink interface.
And a child object can easily be stored in a reference variable of type of its parent.
This is the same as when you wrote this:
List<Integer> list1 = new ArrayList<>();
List is an interface, ArrayList is a class.
It's important to know that if you store a Drink object in a variable type of parent - instead of in a variable of type Drink - then only the methods within the parent class (interface) are available with this variable, the other Drink-methods not.
If you have any further questions, feel free to ask.
0
ImDevin
28 May 2021, 02:39
thx for the reply Gellert. Let me chew on this for a while.
0