1

Arghh I just know people are going to hate me for asking this...

I was just playing around with inheritance and I noticed you can instantiate a subclass object in one of two ways when you write code. So then I wondered if there is any functional difference between these two methods. So in the code below, does this produce the exact same result...a MountainBike object, or is there some difference I should know about? Bicycle is the superclass for this example. If I do Bicycle bike or MountainBike bike I am effectively making a MountainBike due to new MountainBike()? So basically the difference is just semantics at this point?

 Bicycle bike = new MountainBike();
 MountainBike bike = new MountainBike();
Danrex
  • 1,657
  • 4
  • 31
  • 44
  • The object will be the same in memory, but the type of the `bike` *variable* matters, too. – dlev Jun 10 '14 at 03:23
  • 1
    You should read up on polymorphism http://www.tutorialspoint.com/java/java_polymorphism.htm – Bryan Jun 10 '14 at 03:23
  • Functional difference? Yes, if you reference a field, as Java's fields aren't polymorphic. Yes, if you need a `MountainBike`-only member, as the code will compile one way but not the other. No, if you only reference methods. – awksp Jun 10 '14 at 03:23
  • 1
    The type of the *expression* (or variable) is a view - the static/compile-time operations allowed - over the type of the actual *object* therein. – user2864740 Jun 10 '14 at 03:26
  • @user2864740 Isn't that only the case for polymorphic members? I thought the field to use depends on the reference type of `bike` (although that's an issue only if you're shadowing fields, which shouldn't happen...) – awksp Jun 10 '14 at 03:29
  • In simple terms, would only say the behavior will still be provided by the Mountainbike in both the cases. But access to that behavior will be determined by the referencing type. e.g. MountainBike is a specialized bike but you can still use it like a street bike. (underutilizing its capabilities) – Shailesh Aswal Jun 10 '14 at 03:33
  • @user3580294 Depends on how one reads into what "operations allowed" means, but I wasn't too specific ;-) – user2864740 Jun 10 '14 at 03:37
  • @user2864740 Point taken – awksp Jun 10 '14 at 04:28

0 Answers0