This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

abstract and interfaces

 
hemapriya rao
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
could any one tell me the exact difference between abstract and interface class
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) A class can extend only one abstract class but implement multiple interfaces.

2) An interface can only declare constants (any field) and public abstract methods (any method).
An abstract class can have anything other classes can have: private fields, instance fields, protected members, constructors, you name it. Unlike other classes, it can also have abstract methods. Unlike interfaces, these abstract methods can also be protected or have no access modifier.
Please note that they cannot be private - private methods cannot be overridden, and therefore private abstract methods would never get an implementation.
 
hemapriya rao
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1)so,should a immediate subclass of abstract class implement(define) all methods of abstract class?

2)when the class implements interface ,should that class override all methods of the interface?
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For both situations, a class must either implement all abstract methods (so also methods defined inside an interface the class is implementing), or be abstract itself.

If a class is not abstract, it must make sure that all remaining abstract methods must be implemented.

Example:
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15484
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a frequently asked question.
See the answer in the JavaRanch FAQ: InterfaceVsAbstractClass
 
Saurabh Gupta
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like to add one point in term of use of Abstract class and Interface:-

It's generally considered good OO practice to specify the "contract" which you want to adhere to via Java interfaces.

Use abstract Java classes when you want to provide some standard base code but want/need to force the user's of your class to complete the implementation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic