Why to use Interfaces, Multiple Inheritance vs Int

2019-01-01 01:44发布

I still have some confusion about this thing. What I have found till now is

(Similar questions have already been asked here but I was having some other points.)

  1. Interface is collection of ONLY abstract methods and final fields.

  2. There is no multiple inheritance in Java.

  3. Interfaces can be used to achieve multiple inheritance in Java.

  4. One Strong point of Inheritance is that We can use the code of base class in derived class without writing it again. May be this is the most important thing for inheritance to be there.

Now..

Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.

Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?

Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.

Then why to make interfaces ?

NOTE : I have found one case in which interfaces are helpful. One example of it is like in Runnable interface we have public void run() method in which we define functionality of thread and there is built in coding that this method will be run as a separate thread. So we just need to code what to do in thread, Rest is pre-defined. But this thing also can be achieved using abstract classes and all.

Then what are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?

11条回答
梦寄多情
2楼-- · 2019-01-01 02:32

This is very old question and java-8 release have added more features & power to interface.

An interface declaration can contain

  1. method signatures
  2. default methods
  3. static methods
  4. constant definitions.

The only methods that have implementations in interface are default and static methods.

Uses of interface:

  1. To define a contract
  2. To link unrelated classes with has a capabilities (e.g. classes implementing Serializable interface may or may not have any relation between them except implementing that interface
  3. To provide interchangeable implementation e.g. Strategy_pattern
  4. default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces
  5. Organize helper methods in your libraries with static methods ( you can keep static methods specific to an interface in the same interface rather than in a separate class)

Have a look at this related SE question for code example to understanding the concepts better:

How should I have explained the difference between an Interface and an Abstract class?

Coming back to your queries:

Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.

Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?

Interface can contain code for static and default methods. These default methods provides backward compatibility & static methods provides helper/utility functions.

You can't have true multiple inheritance in java and interface is not the way to get it. Interface can contain only constants. So you can't inherit state but you can implement behaviour.

You can replace inheritance with capability. Interface provides multiple capabilities to implementing classes.

Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.

Refer to "uses of interface" section in my answer.

查看更多
旧人旧事旧时光
3楼-- · 2019-01-01 02:32

Inheritance is when one class derives from another class (which can be abstract) or an Interface. The strongest point of object oriented (inheritance) is not reuse of code (there are many ways to do it), but polymorphism.

Polymorphism is when you have code that uses the interface, which it's instance object can be of any class derived from that interface. For example I can have such a method: public void Pet(IAnimal animal) and this method will get an object which is an instance of Dog or Cat which inherit from IAnimal. or I can have such a code: IAnimal animal and then I can call a method of this interface: animal.Eat() which Dog or Cat can implement in a different way.

The main advantage of interfaces is that you can inherit from some of them, but if you need to inherit from only one you can use an abstract class as well. Here is an article which explains more about the differences between an abstract class and an interface: http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

查看更多
骚的不知所云
4楼-- · 2019-01-01 02:35

Interfaces are made so that a class will implement the functionality within the interface and behave in accordance with that interface.

查看更多
只若初见
5楼-- · 2019-01-01 02:40

KISS

I have searched for days, nay weeks trying to understand interfaces and seem to read the same generic help; I'm not trying to disparage the contributions, but i think the light-bulb just clicked so I'm chuffed :))

I prefer to Keep It Simple Stupid, so will proffer my new found view of interfaces.

I'm a casual coder but i want to post this code i wrote in VB.NET (the principle is the same for other languages), to help others understand interfaces.

If i have it wrong, then please let others know in follow up comments.

Explanation

Three buttons on a form, clicking each one saves a different class reference to the interface variable (_data). The whole point of different class references into an interface variable, is what i didn't understand as it seemed redundant, then its power becomes evident with the msgbox, i only need to call the SAME method to perform the task i need, in this case 'GetData()', which uses the method in the class that's currently held by the interface reference variable (_data).

So however i wish to get my data (from a database, the web or a text file), it's only ever done using the same method name; the code behind that implementation...i don't care about.

It's then easy to change each class code using the interface without any dependency...this is a key goal in OO and encapsulation.

When to use

Code classes and if you notice the same verb used for methods, like 'GetData()', then it's a good candidate to implement an interface on that class and use that method name as an abstraction / interface.

I sincerely hope this helps a fellow noob with this difficult principle.

Public Class Form1

Private _data As IData = Nothing

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    _data = New DataText()
    MsgBox(_data.GetData())
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    _data = New DataDB()
    MsgBox(_data.GetData())
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    _data = New DataWeb()
    MsgBox(_data.GetData())
End Sub

End Class

Public Interface IData
Function GetData() As String
End Interface

Friend Class DataText : Implements IData

Friend Function GetData() As String Implements IData.GetData
    Return "DataText"
End Function

End Class

Friend Class DataDB : Implements IData

Friend Function GetData() As String Implements IData.GetData
    Return "DataDB"
End Function

End Class

Friend Class DataWeb : Implements IData

Friend Function GetData() As String Implements IData.GetData
    Return "DataWeb"
End Function

End Class
查看更多
还给你的自由
6楼-- · 2019-01-01 02:43

Interfaces

An interface is a contract defining how to interact with an object. They are useful to express how your internals intend to interact with an object. Following Dependency Inversion your public API would have all parameters expressed with interfaces. You don't care how it does what you need it to do, just that it does exactly what you need it to do.

Example: You may simply need a Vehicle to transport goods, you don't care about the particular mode of transport.

Inheritance

Inheritance is an extension of a particular implementation. That implementation may or may not satisfy a particular interface. You should expect an ancestor of a particular implementation only when you care about the how.

Example: You may need a Plane implementation of a vehicle for fast transport.

Composition

Composition can be used as an alternative to inheritance. Instead of your class extending a base class, it is created with objects that implement smaller portions of the main class's responsibility. Composition is used in the facade pattern and decorator pattern.

Example: You may create a DuckBoat (DUKW) class that implements LandVehicle and WaterVehicle which both implement Vehicle composed of Truck and Boat implementations.

Answers

Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.

Interfaces are not inheritance. Implementing an interface expresses that you intend for your class to operate in the way that is defined by the interface. Inheritance is when you have a common ancestor, and you receive the same behavior (inherit) as the ancestor so you do not need to define it.

Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?

Interfaces do not achieve multiple inheritance. They express that a class may be suitable for multiple roles.

Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.

One of the major benefits of interfaces is to provide separation of concerns:

  • You can write a class that does something with another class without caring how that class is implemented.
  • Any future development can be compatible with your implementation without needing to extend a particular base class.

In the spirit of DRY you can write an implementation that satisfies an interface and change it while still respecting the open/closed principal if you leverage composition.

查看更多
登录 后发表回答