• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interfaces over abstract classes  RSS feed

 
Vinayak Kulkarni
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone give me the detailed explanation of

1. prefering interfaces over abstact classes and vice-versa?

2. Prefering to extending Thread class over implementing runnable interfaces?
 
Shantanu Puranik
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Vinayak,

check the following links

1. Interface Vs. AbstractClass
http://faq.javaranch.com/view?InterfaceVsAbstractClass

2. Implementing Runnable Vs. extending Thread Class
http://www.coderanch.com/t/233239/threads/java/Extending-thread-class
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16049
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. prefering interfaces over abstact classes and vice-versa?

One advantage of using interfaces is that classes in Java can implement multiple interfaces - classes can only extend one class. If you are writing an API, if you provide an interface instead of an abstract class, you are not forcing your users into a specific class hierarchy.

2. Prefering to extending Thread class over implementing runnable interfaces?

Let's have a look at the other way around first: preferring implementing Runnable instead of extending class Thread. If you extend class Thread, your new class inherits the entire public interface of class Thread. That's not always what you want - it's cleaner to implement Runnable instead (that only adds one method to the public interface of your class).

On the other hand, extending Thread makes it simpler for your users to start a thread using your class. If your class would only implement Runnable, users would have to do something like:



But if your class would extend Thread, it would be slightly simpler:

 
Ramen Chatterjee
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When thinking about your interfaces, you might also consider whether you want to add behaviour using interfaces or composition such as in the Strategy Pattern.

For example, if a class implements some behaviour from an interface MyBehaviour, that class can only have the implementation that the class itself specifies. However, if the class had a member of the type MyBehaviour, then the member instance could be any object implementing the interface.

This means that the behaviour could change without changing your class. It also means that the behaviour could be changed dynamically at runtime.

Apologies if this is slightly off topic, but I think it is still relevant to the appropriate use of interfaces

Regards

Ramen
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!