• Post Reply Bookmark Topic Watch Topic
  • New Topic

interface Vs abstract class  RSS feed

 
akhil achuthan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the diff between interface and abstract class? When will you go for abstract class, and when will you go for interface? Please provide any examples if possible
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question that is very frequently asked on the forums here. If you do a search, you'll find that it has been answered many times before.

Also have a look at the answer in the JavaRanch FAQ.
 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check it out!

Java FAQ's

Regards
Thanigaivel S.
 
Rajah Nagur
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you know what your class can do but do not know how; then make it an Interface. i.e. You just know the behaviour; how part is left for the classes implementing this Interface.

Comming to Abstract class:
You know what your class does (i.e. behaviour) but only partially or in a generic way; then you go for Abstract declaration. More concrete implementation will be done by the extending classes.

Tip : Avoid abstract classes and use interfaces

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tip : Avoid abstract classes and use interfaces
Disagree.
Abstract classes can be very useful. This has been discussed before, and check the links given earlier first.

If you have behaviour, but don't know how it is to be implemented, you are looking at an interface. Particularly if you are already inheriting from another class; you can't inherit from two classes in Java. Interfaces have a selection of methods, but all abstract, so they will be implemented differently every time they are used.

If you have entities which can be put into a very general title, you are better off using an abstract class. If you have a method which will be the same in (at least a large majority of) the subclasses, write the method.
If you have a method which will eb different in most cases, use an abstract method.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!