Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface Vs Abstract class

 
Reshma Reddy
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am confusing with Interface and Abstract class I know the concept of these two, and I want to know which one is better (as of I know it depends on the situation rite).

For Ex: in my application I have 200 classes and I have one interface, I am using this interface in 50 classes, In future I will add a new method in interface in that situation I need to override this method in my all classes, it is difficult right.

like this situations which one is better(As of I know abstract class is better is ther any better solution)
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have a FAQ about Interface vs Abstact classes : here.
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reshma reddy wrote:
For Ex: in my application I have 200 classes and I have one interface, I am using this interface in 50 classes, In future I will add a new method in interface in that situation I need to override this method in my all classes, it is difficult right.


"Open to extension close for modification." - Specially if you are coding a program with about 200 classes

Yes but adding a new method to an interface will break all implementation that extend it (It will not break any implementation that use the interface only classes that implement it). Same thing may happen if you add a abstract method to an abstract class.

Also remember in Java we can only extend one class at a time so having a lot of abstract classes create their own problems.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And you might consider a combination of the two using Adapter patterns:


Uh-oh, 200 classes down the road I realize I need to add a 'dropWaste(int size)' method


Now for those implementations deriving from AnimalAdapter that don't need a special version of 'dropWaste' I don't need to modify them. If some animals needs a special implementation of dropWaste I still have to edit those special animals, though. Callers don't care. And, if I come into a multiple - inheritance situation I can implement the Animal interface directly, rather than extend the AnimalAdapter.

A down side is that if all/most of my Animals need a special implementation of dropWaste then I don't get a fancy compile-time warning saying the method wasn't added to the class. The compiler error can save a lot of bugs in the run-time by reminding you of things like this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic