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:19

Both Methods Work (Interfaces and Multiple Inheritance).

Quick Practical Short Answer

Interfaces are better when you have several years of experience using Multiple Inheritance that have Super Classes with only method definition, and no code at all.

A complementary question may be: "How and Why to to migrate code from Abstract Classes to Interfaces".

If you dont have much abstract classes, you may skip interfaces.

Dont rush to use interfaces.

Long Boring Answer

Interfaces are very similar, or even equivalent to abstract Classes.

If your code has many Abstract classes, then its time you start thinking in terms of Interfaces.

The following code with abstract classes:


MyStreamsClasses.java

/* File name : MyStreamsClasses.java */
import java.lang.*;
// Any number of import statements

public abstract class InputStream {
  public void ReadObject(Object MyObject);
}

public abstract class OutputStream {
  public void WriteObject(Object MyObject);
}

public abstract class InputOutputStream 
    imnplements InputStream, OutputStream {
  public void DoSomethingElse();
}

Can be replaced with:


MyStreamsInterfaces.java

/* File name : MyStreamsInterfaces.java */
import java.lang.*;
// Any number of import statements

public interface InputStream {
  public void ReadObject(Object MyObject);
}

public interface OutputStream {
  public void WriteObject(Object MyObject);
}

public interface InputOutputStream 
    extends InputStream, OutputStream {
  public void DoSomethingElse();
}

Cheers.

查看更多
弹指情弦暗扣
3楼-- · 2019-01-01 02:20

Interfaces are collection of final static fields and abstract methods (Newly Java 8 added support of having static methods in an interface).

Interfaces are made in situations when we know that some task must be done, but how it should be done can vary. In other words we can say we implement interfaces so that our class starts behaving in a particular way.

Let me explain with an example, we all know what animals are. Like Lion is an animal, monkey is an animal, elephant is an animal, cow is an animal and so on. Now we know all animals do eat something and sleep. But the way each animal can eat something or sleep may differ. Like Lion eats by hunting other animals where as cow eats grass. But both eat. So we can have some pseudo code like this,

interface Animal {
    public void eat();
    public void sleep();   
}

class Lion implements Animal {
    public void eat() {
        // Lion's way to eat
    }

    public void sleep(){
         // Lion's way to sleep
    }
}

class Monkey implements Animal {
    public void eat() {
        // Monkey's way to eat
    }

    public void sleep() {
        // Monkey's way to sleep
    }
}

As per the pseudo code mentioned above, anything that is capable of eating or sleeping will be called an animal or we can say it is must for all animals to eat and sleep but the way to eat and sleep depends on the animal.

In case of interfaces we inherit only the behaviour, not the actual code as in case of classes' inheritance.

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.

Implementing interfaces is other kind of inheritance. It is not similar to the inheritance of classes as in that inheritance child class gets the real code to reuse from the base class.

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

It is said because one class can implement more than one interfaces. But we need to understand that this inheritance is different than classes' 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.

Implementing an interface puts compulsion on the class that it must override its all abstract methods.

Read more in my book here and here

查看更多
临风纵饮
4楼-- · 2019-01-01 02:22

Old question. I'm suprised that nobody quoted the canonical sources: Java: an Overview by James Gosling, Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four or Effective Java by Joshua Bloch (among other sources).

I will start with a quote:

An interface is simply a specification of a set of methods that an object responds to. It does not include any instance variables or implementation. Interfaces can be multiply-inherited (unlike classes) and they can be used in a more flexible way than the usual rigid class inheritance structure. (Gosling, p.8)

Now, let's take your assumptions and questions one by one (I'll voluntarily ignore the Java 8 features).

Assumptions

Interface is collection of ONLY abstract methods and final fields.

Did you see the keyword abstract in Java interfaces? No. Then you should not consider an interface as a collection of abstract methods. Maybe you are misleaded by the C++ so-called interfaces, which are classes with only pure virtual methods. C++, by design, does not have (and does not need to have) interfaces, because it has mutliple inheritance.

As explained by Gosling, you should rather consider an interface as "a set of methods that an object responds to". I like to see an interface and the associated documentation as a service contract. It describes what you can expect from an object that implements that interface. The documentation should specify the pre and post-conditions (e.g. the parameters should be not null, the output is always positive, ...) and the invariants (a method that does not modify the object internal state). This contract is the heart, I think, of OOP.

There is no multiple inheritance in Java.

Indeed.

JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions. (Gosling, p.2)

Nothing to add.

Interfaces can be used to achieve multiple inheritance in Java.

No, simlpy because there is no multiple inheritance in Java. See above.

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.

That's called "implementation inheritance". As you wrote, it's a convenient way to reuse code.

But it has an important counterpart:

parent classes often define at least part of their subclasses' physical representation. Because inheritance exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks encapsulation" [Sny86]. The implementation of a subclass becomes so bound up with the implementation of its parent class that any change in the parent's implementation will force the subclass to change. (GOF, 1.6)

(There is a similar quote in Bloch, item 16.)

Actually, inheritance serves also another purpose:

Class inheritance combines interface inheritance and implementation inheritance. Interface inheritance defines a new interface in terms of one or more existing interfaces. Implementation inheritance defines a new implementation in terms of one or more existing implementations. (GOF, Appendix A)

Both use the keyword extends in Java. You may have hierarchies of classes and hierarchies of interfaces. The first ones share implementation, the second ones share obligation.

Questions

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.**

Implementation of an interface is not inheritance. It's implementation. Thus the keyword implements.

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

No multiple inheritance in Java. See above.

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 ?/What are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?

The most important question is: why would you like to have multiple-inheritance? I can think of two answers: 1. to give mutliple types to an object; 2. to reuse code.

Give mutliple types to an object

In OOP, one object may have different types. For instance in Java, an ArrayList<E> has the following types: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess, AbstractList<E>, AbstractCollection<E> and Object (I hope I have not forgotten anyone). If an object has different types, various consumers will be able use it without be aware of its specificities. I need an Iterable<E> and you give me a ArrayList<E>? It's ok. But if I need now a List<E> and you give me a ArrayList<E>, it's ok too. Etc.

How do you type an object in OOP? You took the Runnable interface as an example, and this example is perfect to illustrate the answer to this question. I quote the official Java doc:

In addition, Runnable provides the means for a class to be active while not subclassing Thread.

Here's the point: Inheritance is a convenient way of typing objects. You want to create a thread? Let's subclass the Thread class. You want an object to have different types, let's use mutliple-inheritance. Argh. It doesn't exist in Java. (In C++, if you want an object to have different types, multiple-inheritance is the way to go.)

How to give mutliple types to an object then? In Java, you can type your object directly. That's what you do when your class implements the Runnable interface. Why use Runnable if your a fan of inheritance? Maybe because your class is already a subclass of another class, let's say A. Now your class has two types: A and Runnable.

With multiple interfaces, you can give multiple types to an object. You just have to create a class that implements multiple interfaces. As long as you are compliant with the contracts, it's ok.

Reuse code

This is a difficult subject; I've already quoted the GOF on breaking the encapsulation. Other answer mentionned the diamond problem. You could also think of the Single Responsibility Principle:

A class should have only one reason to change. (Robert C. Martin, Agile Software Development, Principles, Patterns, and Practices)

Having a parent class may give a class a reason to change, besides its own responsibilities:

The superclass’s implementation may change from release to release, and if it does, the subclass may break, even though its code has not been touched. As a consequence, a subclass must evolve in tandem with its superclass (Bloch, item 16).

I would add a more prosaic issue: I always have a weird feeling when I try to find the source code of a method in a class and I can't find it. Then I remember: it must be defined somewhere in the parent class. Or in the grandparent class. Or maybe even higher. A good IDE is a valuable asset in this case, but it remains, in my mind, something magical. Nothing similar with hierarchies of interfaces, since the javadoc is the only thing I need: one keyboard shortcut in the IDE and I get it.

Inheritance howewer has advantages:

It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension (Item 17: Design and document for inheritance or else prohibit it). (Bloch, item 16)

An example of a class "specifically designed and documented for extension" in Java is AbstractList.

But Bloch and GOF insist on this: "Favor composition over inheritance":

Delegation is a way of making composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. (GOF p.32)

If you use composition, you won't have to write the same code again and again. You just create a class that handles the duplications, and you pass an instance of this class to the classes that implements the interface. It's a very simple way to reuse code. And this helps you to follow the Single Responsibility Principle and make the code more testable. Rust and Go don't have inheritance (they don't have classes either), but I don't think that the code is more redundant than in other OOP languages.

Furthermore, if you use composition, you will find yourself naturally using interfaces to give your code the structure and the flexibility it needs (see other answers on use cases of interfaces).

Note: you can share code with Java 8 interfaces

And finally, one last quote:

During the memorable Q&A session, someone asked him [James Gosling]: "If you could do Java over again, what would you change?" "I'd leave out classes" (anywhere on the net, don't know if this is true)

查看更多
浪荡孟婆
5楼-- · 2019-01-01 02:23

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

It is not equal inheritance. It is just similiar. Let me explain:

VolvoV3 extends VolvoV2, and VolvoV2 extends    Volvo (Class)
VolvoV3 extends VolvoV2, and VolvoV2 implements Volvo (Interface)

line1: Volvo v = new VolvoV2(); 
line2: Volvo v = new VolvoV3(); 

If you see only line1 and line2 you can infer that VolvoV2 and VolvoV3 have the same type. You cannot infer if Volvo a superclass or Volvo is an interface.

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

Now using interfaces:

VolvoXC90 implements XCModel and Volvo (Interface)
VolvoXC95 implements XCModel and Volvo (Interface)

line1: Volvo   a = new VolvoXC90();
line2: Volvo   a = new VolvoXC95();
line3: XCModel a = new VolvoXC95();

If you see only line1 and line2 you can infer that VolvoXC90 and VolvoXC95 have the same type (Volvo). You cannot infer that Volvo is a superclass or Volvo is an interface.

If you see only line2 and line3 you can infer that Volvo95 implements two types, XCModel and Volvo, in Java you know that at least one has to be an interface. If this code was written in C++, for instance, they could be both classes. Therefore, multiple inheritances.

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.

Imagine a system where you use a VolvoXC90 class in 200 other classes.

VolvoXC90 v = new VolvoXC90();

If you need to evolve your system to launch VolvoXC95 you have to alter 200 other classes.

Now, imagine a system where you use a Volvo interface in 10,000,000 classes.

// Create VolvoXC90 but now we need to create VolvoXC95
Volvo v = new VolvoFactory().newCurrentVolvoModel(); 

Now, if you need to evolve your system to create VolvoXC95 models you have to alter only one class, the Factory.

It is a common sense question. If your system is composed only of few classes and have few updates use Interfaces everywhere is counterproductive. For big systems, it can save you a lot of pain and avoid risk adopting Interfaces.

I recommend you read more about S.O.L.I.D principles and read the book Effective Java. It has good lessons from experienced software engineers.

查看更多
孤独总比滥情好
6楼-- · 2019-01-01 02:27

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.

We can't. Interfaces aren't used to achieve multiple inheritance. They replace it with safer, although slightly less powerful construct. Note the keyword implements rather than extends.

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

They are not. With interfaces a single class can have several "views", different APIs or capabilities. E.g. A class can be Runnable and Callable at the same time, while both methods are effectively doing the same thing.

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.

Interfaces are kind-of multiple inheritance with no problems that the latter introduces (like the Diamond problem).

There are few use-cases for interfaces:

  1. Object effectively has two identities: a Tank is both a Vehicle and a Weapon. You can use an instance of Tank where either the former or the latter is expected (polymorphism). This is rarely a case in real-life and is actually a valid example where multiple inheritance would be better (or traits).

  2. Simple responsibilities: an instance of Tank object in a game is also Runnable to let you execute it in a thread and an ActionListener to respond to mouse events.

  3. Callback interfaces: if object implements given callback interface, it is being notified about its life-cycle or other events.

  4. Marker interfaces: not adding any methods, but easily accessible via instanceof to discover object capabilities or wishes. Serializable and Cloneable are examples of this.

What you are looking for are trait (like in Scala), unfortunately unavailable in Java.

查看更多
皆成旧梦
7楼-- · 2019-01-01 02:27

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.

Unfortunately, in colloquial usage, the word inheritance is still frequently used when a class implements an interface, although interface implementation would be a preferable term - IMO, the term inheritance should strictly be used with inheritance of a concrete or abstract class. In languages like C++ and C#, the same syntax (i.e. Subclass : Superclass and Class : Interface) is used for both class inheritance and interface implementation, which may have contributed to the spread of the misuse of the word inheritance with interfaces. Java has different syntax for extending a class as opposed to implementing an interface, which is a good thing.

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

You can achieve the 'effect' of multiple inheritance through composition - by implementing multiple interfaces on a class, and then providing implementations for all methods, properties and events required of all the interfaces on the class. One common technique of doing this with concrete classes is by doing 'has-a' (composition) relationships with classes which implement the external interfaces by 'wiring up' the implementation to each of the internal class implementations. (Languages such as C++ do support multiple concrete inheritance directly, but which creates other potential issues like the diamond problem).

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.

Interfaces allow existing classes (e.g. frameworks) to interact with your new classes without having ever 'seen' them before, because of the ability to communicate through a known interface. Think of an interface as a contract. By implementing this interface on a class, you are contractually bound to meet the obligations required of it, and once this contract is implemented, then your class should be able to be used interchangeably with any other code which consumes the interface.

Real World Example

A 'real world' example would be the legislation and convention (interface) surrounding an electrical wall socket in a particular country. Each electrical appliance plugged into the socket needs to meet the specifications (contract) that the authorities have defined for the socket, e.g. the positioning of the line, neutral and earth wires, the position and colouring of the on / off switch, and the conformance the the electrical voltage, frequency and maximum current that will be supplied through the interface when it is switched on.

The benefit of decoupling the interface (i.e. a standard wall socket) rather than just soldering wires together is that you can plug (and unplug) a fan, a kettle, a double-adapter, or some new appliance to be invented next year into it, even though this appliance didn't exist when the interface was designed. Why? Because it will conform to the requirements of the interface.

Why use interfaces?

Interfaces are great for loose coupling of classes, and are one of the mainstay's of Uncle Bob's SOLID paradigm, especially the Dependency Inversion Principle and Interface Segregation Principles.

Simply put, by ensuring that dependencies between classes are coupled only on interfaces (abstractions), and not on other concrete classes, it allows the dependency to be substituted with any other class implementation which meets the requirements of the interface.

In testing, stubs and mocks of dependencies can be used to unit test each class, and the interaction the class has with the dependency can be 'spyed' upon.

查看更多
登录 后发表回答