Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

when to use abstract ?  RSS feed

 
adwin wijaya
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems people are prefer to use interface for its flexibility. My question is when wee need to use abstract over interface ?

thanks !
 
Ryan Beckett
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A class must be declared abstract when it has an abstract method. Its common to declare an abstract class when the class represents a base class in a hierarchy. Any extender that's not abstract must implement its abstract methods.

Interfaces are public contracts. They list the signatures of public methods that implementers must implement.
You can't instantiate interfaces (only anonymous inner interfaces) or abstract classes.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65897
135
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I frequently use both. An interface to define the public API, and an abstract base class to provide common implementation.


 
Mo Jay
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Abstract class vs an interface;
An interface is like a 100% Abstract class where ALL the methods are implicitly public abstract and it is up to the class implementing the interface to provide an implementation for all these methods.

On the other hand, the Abstract class might have some OR none of his methods abstract: if you declare just one method to be abstract then you must declare the class to be abstract, however you can still declare a class to be abstract without having any of his methods declared as abstract method. Moreover an abstract class CANNOT be instantiated (ex. you cannot create objects of the abstract class) , it can only be extended so that implementations could be given to the abstract methods if he has any.

I hope this helped clarify the differences.


 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15890
82
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at Interface vs. abstract class in our FAQ.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!