when to use abstract class and when to use interface?

Answer Posted / praveen reddy.e

generally abstract class is written when there are some common features shared by all the objects as they are.

for eg take a class Wholesaler which represents a whole sale shop with text books and stationary like pens,note books etc

class wholesaler
{
void text_books()
{
//text books of X class
}
void stationary();//this can be pens,papers or note books
}

Let us take a Retailer1,a class which represents a retail shop.Retailer1 wants text books of X class and some pens.similarly,Retailer2 also wants text books of X class and some papers.In this case we can understand that the void text_books() is the common feature shared by both the Retailers.But the stationary asked by the Retailers is different.This means ,The stationary has different implementations for different retailers but there is a common feature,i.e,the text books.So in this case,the programer design the Wholesaler class as abstract class.Retailer1 ane Retailer2 as sub classes.
On the other hand, the programer uses an interface if all the features need to be implemented differently for different objects.Suppose,Retailer1 asks for VII class text books and Retailer2 asks for X class books,then even the text_books() of Wholesaler class needs different implementations depending upon the retailer.It means ,the void text_books() and also void stationary() method should be implemented differently depending upon the retailer.So in this case the programer desings the Wholesaler as an interface and Retailer1 and Retailer2 become implementaion classes

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

You're given a Boolean 2D matrix, can you find the number of islands?

864


How to do encapsulation in java?

830


How many digits can a float hold?

769


What is an abstract class and what is it’s purpose?

731


What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

879


What is meant by design patterns?

810


List any five features of java?

794


Do I need to import java.lang package any time? Why?

1062


What is the buffer limit?

768


Are functions objects in java?

809


Why heap memory is called heap?

788


How many days will it take to learn java?

713


What is exception propagation?

845


What is unicode datatype?

727


What is the use of default method in interface in java? Explain

767