Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java abstract class and interface [duplicate]

In interview I have been asked following question. I tried to answer the question but I want exact answer of the question.

If I can simulate Abstract class as Interface, why java provided Interface?

This mean if in Abstract class I can mark all methods as abstract and then abstract class will work as interface, so why I need interface.

Can anyone explain me in brief.

like image 414
Sharad Ahire Avatar asked Feb 23 '11 17:02

Sharad Ahire


People also ask

Can we replace interface with abstract class in Java?

Interfaces can only hold abstract method, also interfaces can implement multiple interfaces to any class. But an abstract hold abstract and non abstract methods, and abstract methods cannot extend to more then one class.

CAN interface have 2 abstract methods?

And in any case, the specification says a functional interface cannot have more than one abstract method. So an interface with two abstract methods cannot be used by specification.

How can abstract classes and methods improve reusability?

If you want to implement or force some methods across classes must be for uniformity you can use an interface. So to increase reusability via inheritance use the abstract class as it is nothing but a base class and to force methods to use interfaces.

Can we use abstract class instead of interface?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.


1 Answers

That's a very standard interview question. The answer is: because you can implement multiple interfaces, but can't extend multiple abstract classes.

Example from the JRE: LinkedList is both a List and a Deque. These interfaces define the behaviour of the class. They do not provide any implementation details. While abstract classes could provide some.

Related questions: this and this. The latter is not directly related, but it shows why are interfaces needed, even in cases when an abstract class would suffice.

like image 70
Bozho Avatar answered Oct 31 '22 13:10

Bozho