Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when to use abstract ?

 
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
Pie
Posts: 65110
89
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
Saloon Keeper
Pie
Posts: 15436
41
Android IntelliJ IDE Java Scala Spring
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic