• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interface Vs Abstract class  RSS feed

 
ParagS Kulkarni
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody tell me in Java, exactly in what kind of situation we have to use interface & not an abstract class?
The typical answer is to achieve multiple Inheritance?
But practically is it the only anwer for that?
 
Bhushan Damle
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Parag S. Kulkarni:
Can anybody tell me in Java, exactly in what kind of situation we have to use interface & not an abstract class?
The typical answer is to achieve multiple Inheritance?
But practically is it the only anwer for that?


Besides this, there is another answer also. That when u implement an interface in several unrelated classes, u can interact with these two classes although there is no physical connection between those(viz. subclass/parent-child relationship). In fact here the term interface comes into existence. It is the interface between two unrelated classes so that they can communicate.
Is it satisfactory?
 
Vj Kamath
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The purpose of an interface is to define only the structure but not the implementation of a class. This is used to define the WHAT and leave the HOW to the implementing class.
But an abstract class can have a partial implementation.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
more correctly, an interface defines behaviour through a contract while an abstract class defines a relation through inheritance.

There are theoretical as well as practical differences between the two.

Saying you implement an interface tells calling classes that "yes, I know how to do this".
Inheriting from an abstract class says "yes, I AM an XXX and therefore I will indeed know how to do this".
It's a far stronger link.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!