File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes when to use abstract ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "when to use abstract ?" Watch "when to use abstract ?" New topic

when to use abstract ?

adwin wijaya

Joined: Oct 01, 2008
Posts: 4
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

Joined: Feb 22, 2009
Posts: 192
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

Joined: Jan 10, 2002
Posts: 63837

I frequently use both. An interface to define the public API, and an abstract base class to provide common implementation.

[Asking smart questions] [About Bear] [Books by Bear]
Mo Jay
Ranch Hand

Joined: Feb 16, 2009
Posts: 83

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

Joined: Aug 16, 2005
Posts: 15080

Have a look at Interface vs. abstract class in our FAQ.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: when to use abstract ?
It's not a secret anymore!