0

For example lets say I have a Car super class and a Honda sub class extending from Car. I understand I can create a Honda object by:

Honda accord = new Honda();

and I can also do:

Car accord = new Honda();

But what are the advantages to instantiating accord as a Car type?

I know if I want to search all Car subclasses I can use if (var instanceof Car), but aside from this are there any special cases?

I'm just having difficulty wrapping my head around this.

Thank You.

Vlad
  • 125
  • 1
  • 1
  • 10
  • @LuiggiMendoza, thanks for noticing. However, interfaces are just a layout for a class, I'm not sure you can instantiate an interface. I'm reading through that post right now. – Vlad Apr 27 '14 at 20:53
  • You can by using an anonymous class. – Luiggi Mendoza Apr 27 '14 at 20:54
  • For the differences between interface and abstract class: http://stackoverflow.com/q/56867/1065197 http://stackoverflow.com/q/761194/1065197 – Luiggi Mendoza Apr 27 '14 at 20:55

1 Answers1

-1

But what are the advantages to instantiating accord as a Car type?

You don't instantiate accord as a Car type. You instantiate an object, which is of type Honda (and also Car) and you define a variable of type Car that points to the object.

abl
  • 5,554
  • 2
  • 21
  • 41
  • There are more differences (advantages) apart of this. – Luiggi Mendoza Apr 27 '14 at 21:00
  • @LuiggiMendoza I didn't intent to point out any advantage or difference (from what?). I just tried to help him understand some concepts. – abl Apr 27 '14 at 21:06
  • Those are already covered in the possible duplicate Q/A. And there are great advantages when programming oriented to interfaces (which is the main question). – Luiggi Mendoza Apr 27 '14 at 21:06
  • @LuiggiMendoza Sorry, I don't see how the main question is about interfaces. The OP is clearly talking about superclasses and subclasses, as clearly stated in the title and the first phrase of the post. The fact that he uses a second example with `List` and `ArrayList` may be because he is perhaps not aware that `List` is an interface. – abl Apr 27 '14 at 21:12
  • That's also covered in the possible duplicate as well, and the answer applies for both interfaces and abstract classes. The only thing to *resolve* would be the difference between abstract classes and interfaces, which is deeply covered in the other links I've posted in the main question in comments. Still, your answer doesn't add any more value to the current info provided there. – Luiggi Mendoza Apr 27 '14 at 21:15
  • @abl, So you're saying the variable I create is Car, but points to a Honda? I'm not understanding the hierarchy here. Or are they both on the same level? And yes, I had completely overlooked the fact that `List` is an interface. My apologies. – Vlad Apr 27 '14 at 21:28