• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference b/w Interface and Abstract  RSS feed

 
AjayEyunni
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell the basic difference between interface and Abstract class. Why we need Interface when abstract class also performs the same task as interface. Only reason is to have the feasibility of implementing more than one interface to a class. If so which is more effiecient to use and when and where interface and abstract classes are used in Java.
 
Marcus Green
arch rival
Rancher
Posts: 2813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An abstract class can have methods with a body, the methods of interfaces cannot have bodies.
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A question that plagued me in my early days of moving from C++ to Java.
I think interfaces are useful as J2EE did away with multiple inheritance. If Java has multiple inheritance, interfaces would probably not be necessary.
So if you want to have a class that promises to be two things then interfaces are the way to go. For example, if a class listens to network traffic and it needs to do its job independently, it can extend whatever class it wants and implement Runnable so that the object of this class can be instantiated and run as a separate thread. In this case, you will extend from a parent class that gives you the network related functionality and by implementing Runnable, you promise that this class can be run independently as a separate thread.
Obviously, an interface is just a dummy. The methods in an interface are a promise or a guarantee, nothing more. The actual responsibility of doing what the interface promises is left to the class implementing that interface.
This is perhaps useful for the clients of a class so that they know what behaviors are not only expected but guaranteed when a class implements an interface.
Note the difference between extending another class or implementing an interface. These are simple English words that have some intuitive sense.
An abstract class can be partly finished so that the child class can fill in appropriate missing info. An interface simply demands that an implementing class implement a certain behavior, leaving it up to the implementing class as to how this is to be done.
In large architectures it's quite common to have abstract classes at the top that provide basic functionality and then specialized child classes.
This is a design question that gets to the point of why a certain construct was put into the language spec. I encourage you to take up a good text book (not the KB one) and read about it and understand it well before proceeding with more advanced topics.
HTH,
Sashi
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!