Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

abstract & interface

 
jidish kumar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you give the real diference between abstract & interface.
where all their needs are more useful in java
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An "interface" is like a contract: it dictates what behavior needs to be defined, but doesn't provide any implementation. There are no instance variables or methods, but only method signatures (method name, parameter list, return type).
An "abstract class" is a class that can't be instantiated, but it can contain instance variables and methods. It assumes that there will be "concrete" classes [non-abstract] that extend the abstract class.
Abstract classes can be used as parent classes when there is a lot of common function/behavior in the child classes that you want to define in a single place. Interfaces are used when you need to define what methods are to be supported, but there is no common functionality because every class that implements the interface will do it in very different ways.
Good examples of interfaces are found in the "java.sql" package. Sun defines the behavior of a Connection (i.e., "close()", "createStatement()", etc.), but they have no way of know how that behavior is to be implemented for each database. Those details are left up to the driver providers.
The other difference lies in the fact that Java defines a single-inheritance model, meaning a child class can extend only one parent class. However it can implement as many interfaces as it needs to, so you get some of the benefits of multiple inheritance w/out many of the issues.
Interfaces also allow you to easily plug in different classes at run-time, as long as they all implement the target interface.
I'm sure others can explain it better, but if you search the web I'm sure you find many other explanations as well. (Here's a quick one: The Java Boutique).
[ September 17, 2003: Message edited by: Wayne L Johnson ]
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since this doesn't have anything to do with GUIs or Graphics directly, I'm moving this topic to Java in General.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a *very* frequently asked question - doing a search should give you many past discussions on exactly this topic.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic