This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Abstract class  RSS feed

 
navat venu
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could anyone please explain in which scenario abstract class will be used and in which scenario interface is used?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an advanced question. Moving...
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please do a search for "difference between abstract class and interface" or something similar; this question is asked frequently on the forums here, so you will quickly find a lot of answers.
 
K Kiran Kumar
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abstract class consists of concrete methods and abstract methods.
Interface Consists of only abstract methods and final variables.

public class animal
public class Lion extends animal
public class Cow extends animal

Take an example of animal class.
Take the method definition of eating contents. For Lion class, this will be meat. But for Cow class this will be only grass.
Take one more parameter of legs and tail. For both the above classes the legs and tail definition is same.

So here we have to use abstract class because One legs and tail is same for both the classes Lion and Cow and that method is defined in super class animal. The other method eating() is overridden by the subclasses to define their own definition based on the specific animal.

For interfaces, all the method definitions will be specific to each sub class. So they will be only defined in the interface and is implemented in the subclass as per the functionality which is specific. In the above example if there is only one method i.e., eating() and if we don't consider legs and tail() method, then it is obvious that we should use interface rather than abstract class.

"Moreover there are not any hardcore rules that for this we have to use Abstract class and for that we have to use interfaces". We can nearly implement in interface everything what all we are implementing in abstract class and vice versa. Also remember that abstract class consists of contrete methods and abstract methods.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!