• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use Interfcae and abstract class

 
Akhilesh Yadav
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please tell the use of interfce and abstract class

when to use interface and when to use abstract class
 
Quintin Stephenson
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for a better understanding of interfaces read:
http://java.sun.com/docs/books/tutorial/java/concepts/interface.html

for a better understanding of abstract classes read:
http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html

hope these pages help.
Cheers
Q
 
Dilraj Singh
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Akhlesh Hi,

Use absract class:

1. when you are sure classes that supposed to extend the abstract class will always need to follow behaviour that you are providing.

2. you want users not to change this functionality in future in their derived classes.

for example, for car engines, you might want to make "BasicEngineFuntion" as a abstract class that defines following function :

1.CarborrettorSpark() {// make spark in carborretor when some condition is met}

If it is not clear let me know.
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can always rewrite an abstract class plus subclasses, without using an abstract class. You cannot always rewrite interfaces plus implementations as abstract classes. Therefore abstract classes are more limited. Their advantage is that they're easy to teach.

Another construct that's easy to teach, but causes problems in larger programs, is 'goto'. (Java doesn't support goto anyway). So just because something is easy to teach, doesn't mean it's going to be that useful.
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FAQ: InterfaceVsAbstractClass
 
Andy Morris
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I generally define interfaces for everything, and then when appropriate provide abstract implementations of those interfaces. This gives the choice to concrete classes to extend from an abstract class or completely re-implement the interface/contract. Either way, calling code only needs to depend on the interface, which is something that can be defined very early on and is not tied to a specific implementation.
[ April 27, 2007: Message edited by: Andy Morris ]
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic