What to choose between abstract class and interface if…

Answer to what to choose between abstract class and interface if both contain only abstract methods.

This is the frequently asked technical interview question. Here I’m providing two reasons with examples.

Let me elaborate the question for your better understanding.

You know that interface contains only abstract methods. But, consider the restriction that abstract class has only abstract methods only, then what would be your choice and why? Here is an example.

interface Doc{
	abstract void header();
	abstract void body();
	abstract void footer();
}
abstract class Doc{
	abstract void header();
	abstract void body();
	abstract void footer();
}

Answer:

Best choice is an interface for two reasons given below.

1)Missing a chance of multiple inheritance

Since multiple inheritance is not supported in java, you cannot inherit your class from two abstract classes or one abstract and other concrete class. But, if you use interface the still you have a chance to extend a class.

For given interface and classes below, you cannot extend two classes but interface

interface X{	}
abstract class A{}
class B{}

class C extends A implements X{}//OK, on class and multiple interfaces can be extended and implemented.

class C extends A ,B{} // wrong, two classes cannot be extended.

2) User / Programmer intent:

Depending what you choose between abstract class and interface to provide contracts, your contracts can be easily violated by users or programmer’s intent.

Let’s consider a scenario.

Let’s say you are a client and pass the contracts in an interface to implement them to development team for multiple types of documents e.g. pdf, rtf and word etc. Constricts example is below, that team need to implement header, body and footer.

interface Doc{
	abstract void header();
	abstract void body();
	abstract void footer();
}

All development team understand easily that they must just implement and do nothing extra. this is what you want as a result.

Now you pass these contracts in an abstract class as below.

abstract class Doc{
	abstract void header();
	abstract void body();
	abstract void footer();
}

Programmers from team get intention that they are free to implement another interface besides given one in abstract class.

Also, they can write their own methods (private or public) into the abstract class, if they think it is required during implementation of sub classes i.e. pdf, rtf and word etc. This is not the client want.

Related Posts