wood burning stoves 2.0*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "when to use abstract ?" Watch "when to use abstract ?" New topic
Author

when to use abstract ?

adwin wijaya
Greenhorn

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
Marshal

Joined: Jan 10, 2002
Posts: 61066
    
  66

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



[Asking smart questions] [Bear's FrontMan] [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: 14114
    
  16

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


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: when to use abstract ?