Java abstract class and interface [duplicate]

2020-02-22 06:38发布

问题:

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.

回答1:

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.



回答2:

Interfaces define contracts & can define constants, but provide no implementation at all of the contracted methods.

Abstract classes can provide implementations of methods as well as member variables - if you want you can create an abstract class that defines everything except the fine-tuning you want in your concrete subclasses. You can't do this with interfaces, but you can implement multiple interfaces & extend only one parent class.

Both interfaces & abstract classes can be used to make use of concrete classes polymorphically.



回答3:

Abstract classes do well to set default methods and set up the hierarchy. The issue is subclasses may only extend a superclass one-time. Interfaces on the other hand can extend each other multiple times and subclasses can implement any number of interfaces. This provides a lot of flexibility and affords the potential for change. Ideally, the can be combined i.e. abstract class implements interface1…interface2, best of both worlds.



回答4:

The reason why interviewers ask this question is because your answer reflects your deep understanding of what a programming language (and a compiler) is. In particular, Java defines the concept of interface on top of (pure) abstract classes in order to (partially) support multiple inheritance (between interfaces). If this mechanism had not been introduced, we would have either no way of achieving some sort of multiple inheritance, or the big mess created by fully-fledged multiple inheritance in C++.



回答5:

Answer

1) MULTIPLE INHERITANCE in java is achieved through interfaces.

2) If there is a situation where some explanation of a method is required, but not a full fledged one, the best way is to use abstract class.

3)Interfaces merely provide an AGREEMENT for the return type and the argument types.