I'm confused about an OOP feature, multiple inheritance. Does OOP allow Multiple Inheritance? Is Multiple Inheritance a feature of OOP? If Multiple Inheritance is a feature then why don't languages like C#, VB.NET, java etc. support multiple inheritance? But those languages are considered as strongly supported OOP language. Can anyone address this question?
There is no requirement in OO to support multiple inheritance, which is supported by languages such as C++. C# and Java don't support and they are no less OO because of that.
Inheritance doesn't have anything to do with object orientation. There's plenty of OO languages that do not support inheritance at all and there's plety of non-OO languages that do support inheritance. Those two things are completely orthogonal.
Please take a look at Diamond Problem
Languages like Java and C# , which is highly inspired from java as matter of Object Oriented Principles, are built for application making development,so the designers of these kind of languages decided to take approach in which OOP can be understandable and quickly be learnt by developers.So, for the sake of simplicity and clarification of responsibilities of each class in inheritance, they avoid considering one object inherit from multiple objects.Instead they consider using Interfaces in order to implement multiple very different behaviors and attributes.With this in mind the principles of:
Single responsibility of each object ,and transparent segregation of responsibility of each interface and subsequent inherited objects be fully understandable.
Multiple inheritance refers to a feature of SOME object-oriented programming languages, not all of them.
These other languages you are referring to use interfaces.
First, you have to distinguish between multiple inheritance and multiple supertypes, these are two very different things.
Multiple inheritance usually reflects to an actual inheriting of implementation (like class inheritance in most OOP languages) and presents a variety of concerns. One is conflict between names and implementations (e.g., two methods with same name and a different implementation), and then issues like the idamond problem.
Multiple supertypes usually refers to the ability to check types (and in some cases cast), and usually does not involve inheriting implementations. For example, in Java you have interfaces that merely declare your methods. So your subtype supports the union of the method supported by the supertypes. This presents less problems because you do not have a method with multiple implementations.
Multiple inheritance usually involves multiple supertypes, though some languages like C++ allow you modify the visibility of this fact (e.g., who can know that type B is a subtype of type A).
To the best of my knowledge, there is no requirement for an OOP language to support either, but at least multiple-supertypes is necessary for a usable OOP language where most design patterns can be implemented in a straightforward way. Multiple inheritance, IMHO, is really not that useful to justify the complexity and costs. I've made the switch to Java ten years ago and can't say that I missed it too much.
Java
Multiple inheritence in Java is quite possible. But there are certain restrictions that Java has.
Java classes do not support multiple inheritances but java interfaces do support multiple inheritances
Java Classes
public class elderchild
{
\\elder child attributes
}
public class middlechild
{
\\middle child attributes
}
public class parent extends middlechild, elderchild \\this is wrong, multiple class inheritance is restricted
{
\\parent attributes
}
Java Interfaces
public interface animal
{
\\animal attirbutes
}
public interface mammal
{
\\mammal attributes
}
public class dog implements animal, mammal \\this is correct!
{
\\dog attributes
}
Note: The diamond problem can also occur in java. To read more about it, open:
https://stackoverflow.com/questions/29758213/multiple-inheritance-ambiguity-with-interface#:~:text=Java%20doesn't%20support%20multiple,methods%20will%20have%20same%20signature.
Related
I heard that interface is introduced as a way for making up that a object-oriented language doesn't support multiple inheritance but only single inheritance.
Is interface merely used for that purpose?
Is interface ever useful for a OO language which supports multiple inheritance?
Thanks.
The book "Design Patterns" strongly stresses the importance of interfaces and at the time it was written, C++ (with multiple inheritance) was the most popular OO language and Java didn't even exist yet. (The book was published a year before Java was released.)
It's important to understand the difference between an object's class and its type.
An object's class defines how the object is implemented... In contrast, an object's type only refers to its interface—the set of requests to which it can respond.
...
It's easy to confuse these two concepts, because many languages don't make the distinction explicit.
...
Many of the design patterns depend on this distinction.
This book coined the term "Program to an Interface, not an Implementation."
I could not find the main difference. And I am very confused when we could use inheritance and when we can use subtyping. I found some definitions but they are not very clear.
What is the difference between subtyping and inheritance in object-oriented programming?
In addition to the answers already given, here's a link to an article I think is relevant.
Excerpts:
In the object-oriented framework, inheritance is usually presented as a feature that goes hand in hand with subtyping when one organizes abstract datatypes in a hierarchy of classes. However, the two are orthogonal ideas.
Subtyping refers to compatibility of interfaces. A type B is a subtype of A if every function that can be invoked on an object of type A can also be invoked on an object of type B.
Inheritance refers to reuse of implementations. A type B inherits from another type A if some functions for B are written in terms of functions of A.
However, subtyping and inheritance need not go hand in hand. Consider the data structure deque, a double-ended queue. A deque supports insertion and deletion at both ends, so it has four functions insert-front, delete-front, insert-rear and delete-rear. If we use just insert-rear and delete-front we get a normal queue. On the other hand, if we use just insert-front and delete-front, we get a stack. In other words, we can implement queues and stacks in terms of deques, so as datatypes, Stack and Queue inherit from Deque. On the other hand, neither Stack nor Queue are subtypes of Deque since they do not support all the functions provided by Deque. In fact, in this case, Deque is a subtype of both Stack and Queue!
I think that Java, C++, C# and their ilk have contributed to the confusion, as already noted, by the fact that they consolidate both ideas into a single class hierarchy. However, I think the example given above does justice to the ideas in a rather language-agnostic way. I'm sure others can give more examples.
A relative unfortunately died and left you his bookstore.
You can now read all the books there, sell them, you can look at his accounts, his customer list, etc. This is inheritance - you have everything the relative had. Inheritance is a form of code reuse.
You can also re-open the book store yourself, taking on all of the relative's roles and responsibilities, even though you add some changes of your own - this is subtyping - you are now a bookstore owner, just like your relative used to be.
Subtyping is a key component of OOP - you have an object of one type but which fulfills the interface of another type, so it can be used anywhere the other object could have been used.
In the languages you listed in your question - C++, Java and C# - the two are (almost) always used together, and thus the only way to inherit from something is to subtype it and vice versa. But other languages don't necessarily fuse the two concepts.
Inheritance is about gaining attributes (and/or functionality) of super types. For example:
class Base {
//interface with included definitions
}
class Derived inherits Base {
//Add some additional functionality.
//Reuse Base without having to explicitly forward
//the functions in Base
}
Here, a Derived cannot be used where a Base is expected, but is able to act similarly to a Base, while adding behaviour or changing some aspect of Bases behaviour. Typically, Base would be a small helper class that provides both an interface and an implementation for some commonly desired functionality.
Subtype-polymorphism is about implementing an interface, and so being able to substitute different implementations of that interface at run-time:
class Interface {
//some abstract interface, no definitions included
}
class Implementation implements Interface {
//provide all the operations
//required by the interface
}
Here, an Implementation can be used wherever an Interface is required, and different implementations can be substituted at run-time. The purpose is to allow code that uses Interface to be more widely useful.
Your confusion is justified. Java, C#, and C++ all conflate these two ideas into a single class hierarchy. However, the two concepts are not identical, and there do exist languages which separate the two.
If you inherit privately in C++, you get inheritance without subtyping. That is, given:
class Derived : Base // note the missing public before Base
You cannot write:
Base * p = new Derived(); // type error
Because Derived is not a subtype of Base. You merely inherited the implementation, not the type.
Subtyping doesn't have to be implemented via inheritance. Some subtyping that is not inheritance:
Ocaml's variant
Rust's lifetime anotation
Clean's uniqueness types
Go's interface
in a simple word: subtyping and inheritance both are polymorphism, (inheritance is a dynamic polymorphism - overriding). Actually, inheritance is subclassing, it means in inheritance there is no warranty to ensure capability of the subclass with the superclass (make sure subclass do not discard superclass behavior), but subtyping(such as implementing an interface and ... ), ensure the class does not discard the expected behavior.
The necessity for protocols are to abstract the methods of classes which are not hierarchically related.
The similar things also can be done with the help a class (interface) which encompasses all those methods and subclass them ? (This is not really possible due to the Multiple inheritance problem since a class has to be derived already from NSObject.ignore the NSProxy case)
What special things that protocols can do than a class?
Are protocols trying to solve only the multiple inheritance problem?
Protocols main advantage is, that they describe what a object should be able to do, without enforcing subclassing. In languages that dont have multiple inheritance such a mechanism is needed, if you want others programmers be able to use your classes. (see delegation)
For an instance Java has something similar, called interfaces.
This means a huge advantage, as it is very easy to build dynamic systems, as I can allow other developers to enhance my classes via a clearly defined protocol.
A practical example:
I am just designing a REST API and I am providing a Objective-C client library.
As my api requires information about the user, I add a protocol
#protocol VSAPIClientUser <NSObject>
-(NSString *)lastName;
-(NSString *)firstName;
-(NSString *)uuid;
#end
Anywhere I need this user information, I will have an basic id-object, that must conform to this protocol
-(void)addUserWithAttributes:(id<VSAPIClientUser>)user;
You can read this line as: "I don't care, what kind of object you provide here, as long as it knows about lastName, firstName and uuid". So I have no idea, how the rest of that object looks like — and I don't care.
As the library author I can use this safely:
NSDictionary *userAttributes = #{#"last_name" : [user lastName],
#"first_name": [user firstName],
#"uuid": [user uuid]};
BTW: I wouldn't call the absence of multi-inheritance a problem. It is just another design.
“[…] If I revisited that decision today, I might even go so far as to remove single inheritance as well. Inheritance just isn’t all that important. Encapsulation is OOP’s lasting contribution.” — Brad Cox was asked, why Objective-C doesn’t have multiple inheritance. (Masterminds of Programming: Conversations with the Creators of Major Programming Languages, p. 259)
As an alternative view....
Object-oriented programming's most basic value comes from being able to model real-world relationships directly as opposed to translating them into abstract and vaguely-equivalent computer-world constructs. Wherever a language requires you to think about the implementation of a solution in different terms than those you can use to describe your problem, it is flawed as an OOP tool. (Note that I didn't say 'useless'. :) )
Real-world objects have various roles that depend on context. Those roles can have state. Therefore, I agree that lack of multiple-inheritance is an impediment to ease of modelling. Objective-C protocols, Java interfaces, and the claim that you should prefer composition to inheritance are all denials of a fundamental part of the OOP advantage.
One of many uses of C++ abstract classes is, among their other uses, to define interfaces (to specify reusable contracts). There are however also other programming languages, such as Objective C that have a separate concept for interfaces in this sense; in Objective C, it is called protocols.
A wide use of such a construct does require a way of attaching more than one contract to an object; and if such interfaces are allowed to inherit from each another, this has to be multiple inheritance to be useful.
However, this is not the same thing as multiple inheritance between classes.
Protocols are not trying to solve the multiple inheritance problem. They are trying to separate contract specification from object (data+code) specification. They can actually do much less than a class (if you ignore the multiple inheritance aspect) and that's why they exist as a separate concept.
Implementing a protocol is generally a much less restrictive (safer) proposition to consider than inheriting from a class.
I'm reading through Design Patterns by GoF and I'm starting to wonder. Are interfaces redundant if you're using an abstract as the interface in languages like C#? Let's put multiple inheritance aside for a moment, as I understand you can only achieve that (in C#) through interfaces.
I'm trying to apply this logic to DDD in C#. Almost every example and implementation I've ever seen uses interfaces. I'm starting to wonder why. Could the abstract class be used instead? It seems to me that this would be a more robust solution, but then again I could be missing something, which is why I'm asking here.
Summary:
Question 1: In the context of OOP with a language that only supports single inheritance, if designed properly what are some uses
of interfaces over the abstract class?
Question 2: In the context of DDD, if designed properly what are the uses of interfaces over the abstract class?
Note:
I've read through all the similar questions listed, but none seem to give me an answer. If I missed one, please let me know.
For question 1: regardless of support for multiple inheritance interfaces are contract specifications, abstract classes are base classes.
Interfaces provide a way for a class to specify a set of capabilities ( think IDisposable, IEnumerable, etc ) and it's recommended that they obey the Interface Segregation Principle.
Abstract classes should implement a concept that can be extended, or that can have different implementations depending on the context ( think HttpContextBase, AbstractButton etc ).
The biggest difference between interfaces and abstract classes is conceptual. You can argue that, except inheritance, an interface is the same as an abstract class with only abstract methods, but conceptually they represent different things.
As for question 2: in the context of DDD interfaces are implementations details. I dare say you can do DDD and not use interfaces or abstract classes, or even inheritance. As long as you have your bounded contexts, aggregates, entities and VOs well defined.
In conclusion, when you try to express a contract use an interface, when you want to indicate that your class has some capability, implement an interface. When you have a concept for which you can provide more implementations depending on context, use a base class ( abstract or not ).
When you think about it like this, the decision of the language makers ( c# ) to allow only single inheritance, but allow implementation of multiple interfaces makes a lot of sense.
The advantage of Interfaces is precisely that there is no multiple-inheritance. By using an Interface you can allow classes like Forms, UserControls, Components, etc to participate in interactions that would otherwise be diffucult/impossible.
I recommend doing both. I usually create an interface, and (if possible) then create an abstract class that inherits that interface to provde any common or default implementaion of that interface. This gives you the best of both worlds.
interfaces are not redundant. an interface is independent of implementation while abstract classes are implementation. code that uses an interface does not have to be changed or recompiled if some implementation class changes.
the advantage is above. if you are doing ddd, start out with concrete classes and write some tests. refactor common stuff into base classes (some will be abstract). if there is a reason to make an interface go ahead and do so. repeat until done.
This is not yet another question about the difference between abstract classes and interfaces, so please think twice before voting to close it.
I am aware that interfaces are essential in those OOP languages which don't support multiple inheritance - such as C# and Java. But what about those with multiple inheritance? Would be a concept of interface (as a specific language feature) redundant in a language with multiple inheritance? I guess that OOP "contract" between classes can be established using abstract classes.
Or, to put it a bit more explicitly, are interfaces in C# and Java just a consequence of the fact that they do not support multiple inheritance?
Not at all. Interfaces define contracts without specifying implementations.
So they are needed even if multiple inheritance is present - inheritance is about implementation.
Technically, you can use an abstract class in multiple inheritance to simulate an interface. But thus one can be inclined to write some implementation there, which will creates big messes.
Depends on the test for redundancy.
If the test is "can this task be achieved without the language feature" then classes themselves are redundant because there are Turing compete languages without classes. Or, from an engineering base, anything beyond machine code is redundant.
Realistically, the test is a more subtle combination of syntax and semantics. A thing is redundant if it doesn't improve either the syntax or the semantics of a language, for a reasonable number of uses.
In languages that make the distinction, supporting an interface declares that a class knows how to converse in a certain manner. Inheriting from another class imports (and, probably, extends or modifies) the functionality of another class.
Since the two tasks are not logically equivalent, I maintain that interfaces are not redundant. Distinguishing between the two improves the semantics for a large number of programs because it can more specifically indicate programmer intent.
... The lack of multiple inheritance
forced us to add the concept of
interfaces...
Krzysztof Cwalina, in The C# Programming Language (4th Ed.) (p. 56)
So yes, I believe interfaces are redundant given multiple inheritance. You could use pure abstract base classes in a language supporting multiple inheritance or mix-ins.
That said, I'm quite happy with single inheritance most of the time. Eric Lippert makes the point earlier in the same volume (p. 10) that the choice of single inheritance "... eliminates in one stroke many of the complicated corner cases..."
There are languages that support multiple inheritance that do not include a parallel concept to the Java interface. Eiffel is one of them. Bertrand Meyer did not see the need for them, since there was the ability to define a deferred class (which is something most folks call an abstract class) with a fleshed out contract.
The lack of multiple inheritance can lead to situations where a programmer needs to create a utility class or the like to prevent writing duplicated code in objects that implement the same interface.
It may be that the presence of the contract was a significant contribution to the absence of a completely implementation free concept of an interface.... Contracts are harder to write without some implementation details to test against.
So, technically interfaces are redundant in a language that supports MI.
But, as others have pointed out... multiple inheritance can be a very tricky thing to use correctly, all the time. I know I couldn't... and I worked for Meyer as he was drafting Object Oriented Software Construction, 2nd edition.
Are interfaces in C# and Java just a
consequence of the fact that they do
not support multiple inheritance?
Yes, they are. At least in Java. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple). Java's designers chose to allow multiple interface inheritance through the use of interfaces, an idea borrowed from Objective C's protocols.
See there for details
And, yes, I believe that like in C++ Interfaces are redundant, if you have multiple inheritance. If you have a more powerful feature, why to keep the less one?
Well, if you go this way, you could say that C and C++, C# and oll other high level languages are redundant because you can code anything you want using assembly. Sure you don't absolutely need these high level languages, however, they help ... a lot.
All these languages come with various utilities. For some of them, the interface concept is one of these utilities. So yes, in C++, you could avoid using interfaces an stick with abstract classes without implementation.
As a matter of fact, if you want to program Microsoft COM with C, although C doesn't know the interface concept, you can do it because all .h files define interfaces this way:
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("ABCDE000-0000-0000-0000-000000000000")
IMyInterface : public IUnknown
{
...
}
#else /* C style interface */
typedef struct IMyInterfaceVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *SomMethod )(... ...);
END_INTERFACE
} IMyInterfaceVtbl;
interface IMyInterface
{
CONST_VTBL struct IMyInterfaceVtbl *lpVtbl;
};
#endif
Some kind of another syntactic sugar...
And it's true to say that in C#, if I hadn't the interface concept, I don't know how I could really code :). In C#, we absolutely need interfaces.
Interfaces are preferable to multiple inheritance since inheritance violates encapsulation according to "Effective Java" Item 16, Favor composition over inheritance.