0

Is there any difference between these? If they are different what is the difference and why would you use one vs the other?

IMyInterface myObject = new ConcreteClass();

vs

ConcreteClass myObject = new ConcreteClass();

BTW I'm not looking for a definition of polymorphism or inheritance, more an example of where you would need to use the first line.

erotavlas
  • 4,274
  • 4
  • 45
  • 104
  • 1
    Yes; your variables have different compile-time types. – SLaks Mar 25 '14 at 16:21
  • [Polymorphism](http://en.wikipedia.org/wiki/Polymorphism_(computer_science)) – Liam Mar 25 '14 at 16:22
  • @Liam This particular different wouldn't change whether or not your code is polymorphic. Both could be, and both could not be, polymorphic. – Servy Mar 25 '14 at 16:22
  • 1
    For first case:`IMyInterface myObject = new ConcreteClass();` If you have concrete class object in interface object, then you can only access interface members through it. You can't access concrete class members through it. For second case:`ConcreteClass myObject = new ConcreteClass();` You loose the polymorphic behaviour. – user2711965 Mar 25 '14 at 16:24
  • 1
    @NewHire No polymorphic behavior is lost in the second case. Both can potentially exhibit polymorphic behavior. – Servy Mar 25 '14 at 16:25
  • So this would be useful, say if some concrete implementations have varying members or methods, but you want to hide those so they are inaccessible when using myObject downstream (i.e. force to use only the interface members)? – erotavlas Mar 25 '14 at 16:29

0 Answers0