0

Is there any difference for below code

  1. AbstractClass object = new SubClass();(SubClass is a class that extended the AbstractClass)

  2. SubClass object = new SubClass();

In both the scenarios subclass extended the Abstract Class and implemented the methods of Abstract Class

  • no difference, i find – Faraz Feb 20 '16 at 19:23
  • @HovercraftFullOfEels: This question isn't asking about an interface. – Makoto Feb 20 '16 at 19:28
  • @Makoto: true, but the concept is the same. And regardless, this question has been asked so often, and it is quite surprising that the OP didn't find the duplicate before posting. – Hovercraft Full Of Eels Feb 20 '16 at 19:30
  • @Makoto But the principle to _code to an interface_ is the same for abstract classes. In fact, you could exchange "interface" with "most general type in the type hierarchy", couldn't you? – Seelenvirtuose Feb 20 '16 at 19:31
  • @Seelenvirtuose: If the OP were asking, "Why should I...?", then yes, this would be a suitable duplicate. However, there is an acute difference when working with a concrete and abstract class (especially if the concrete instance has implemented other methods). – Makoto Feb 20 '16 at 19:33

1 Answers1

1

The first one is preferred: you're declaring a variable of a more general type, and if the need arises, you could polymorphically substitute it for another object instance as long as it also extends from the same abstract class.

In the GoF book they state this principle as "Program to an interface, not an implementation" (technically AbstractClass isn't an interface, it's an abstract class, but the same principle applies.)

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thank you for clarifying the doubt – user2514421 Feb 20 '16 at 19:39
  • @user2514421 If this answer was helpful for you, please don't forget to [accept](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it, just click on the check mark to its left ;) – Óscar López Feb 20 '16 at 19:39