Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when to use abstract class and when to use an interface

 
Satyajeet Kadam
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q1)when to use abstract class and when to use an interface?

Q2) When i should use one over the other? with an example

Q3) Performance wise who will be faster?
 
rushikesh sawant
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use abstract class when you have some implementation that a group of subclass should use.
Also use abstract class to make sure that its instance cannot be created.

use an interface when you want all other classes to implement all methods in interface though those classes are not from same inheritance tree. interface generally defines a role that implementing classes should play.

and as for performance, i am not sure. may be both perform at same speed or may be its java virtual machine dependent. and why do you care about such a minute change in speed?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally it's consider better practice to use interfaces over abstract classes which follows the principle 'favor composition over inheritance'. But this is more like a rule of thumb and when there is a good reason for using an abstract class then go right ahead.
 
PrasannaKumar Sathiyanantham
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you want to force your subclass to implement all the methods of the superclass change it to interface.


Abstract classes are seldom in use
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at this faq...
 
Allan Cheong
Ranch Hand
Posts: 71
Eclipse IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I find that abstract class is very useful to implement to Template Method pattern.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65218
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PrasannaKumar Sathiyanantham wrote:Abstract classes are seldom in use

Nothing could be further from the truth.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic