I have this confusion for long time. Many people says we can achieve multiple inheritance by interfaces in languages like C# or Java which does not support it like C++ does. But my understanding of inheritance and interface says no. Because interfaces are contracts to validate an implementation which has nothing to do with behavior. Interface defines what something can do (not what something is). But inheritance is inheriting behavior and/or property from parents (like a child is getting some genetic behavior from his parent - which is inheritance). Now the child is learning a skills say painting and cooking and the interface (a certificate or contract) acts as a validation that the child is having such skills (that is what the child can do other than what he got from his parents - and that's not inheritance)
So am I understanding it wrong? And if not then why it is saying that we can achieve multiple inheritance using interfaces?
Interfaces give you multiple inheritance of a type, but not behaviour. A class implementing List and Map is a "ListMap", but the implementation has nothing (necessarily) to do with any existing List or Map implementation.
Of course using composition (which should be favored anyways), you could easily create a ListMap which delegates the calls accordingly to its list and map properties, while providing some presumably useful function that would combine their respective data.
With Java 8 interfaces are allowed default methods, so inheritance of behaviour is now also possible.
In Java you can create an interface for example Animal and an abstract class Bird.
then you can have a class MockingBird which extends the behavior of Bird and implements the actions of an Animal.
However, you can then address MockingBird as an Animal or as a Bird because it "inherits" from both.
No, interfaces cannot be used to achieve multiple inheritance
Not at all in Java, in C#, we can get closer.
I studied this matter when I wanted to implement an observer, and ended up in Robert Martin's blog: http://blog.cleancoder.com/uncle-bob/2015/01/08/InterfaceConsideredHarmful.html
After reading this post I realized he's talking about Java, but C# supports extension methods which allow you to attach behaviour on interfaces so I tried to make my implementation on some IObservable interface but obviously failed, even if I can attach behaviour in such interfaces extension methods I'm still not allowed for attaching state on them, if some day microsoft decides to implement extension properties then this combination (Interface + Extension methods + Extension properties) could be sufficient to truly simulate some useful multiple inheritance.
For now, we are stuck with duplicating the code, or the delegation code in all our observers as stated in the blog.
Related
I know this question has been asked many times and we have articles all over the internet but I still cannot fully understand, when should I use interface or abstract class since I am using Java 15.
Most of the articles talk about the differences and use cases before Java 8 which makes sense but not when you can basically provide body for your methods in interface.
The only thing that made sense to me is non-public and non-final restrictions.
I would really appreciate if somebody can point out 1-2 examples of the scenarios where I need to choose between interface and abstract class in Java 15. Also, would be great if it can be in terms of real life projects rather than Animal or shape class examples.
Thanks !!
default methods on interface
Apparently you are referring to the feature of “default methods” implementing behavior in an interface.
You should understand that the feature was added as a way around this dilemma: How to retroactively add features leveraging streams and lambda on existing interfaces without breaking existing classes that implement those interfaces?
Many new methods were added to those interfaces such as in the Java Collections Framework. Adding methods to an existing interface would automatically break all classes implementing the interface that are lacking the newly-required methods. Being able to provide a fallback, to give an implementation where one is now required but not yet existing, would resolve the dilemma. Thus « default methods » were born.
To quote from the Oracle tutorial linked above:
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.
To quote this Answer by Brian Goetz, Java Language Architect at Oracle:
The proximate reason for adding default methods to interfaces was to support interface evolution
So this feature of adding default behavior to an interface was not meant to be a new mainstream feature in and of itself. The intent of default was not to replace abstract.
Indeed, some experienced Java experts have recommended against making a habit of writing default methods on an interface. They recommend pretty much ignoring that feature of the Java language. Continue to think of interfaces as simply defining a contract, and abstract classes as providing partial implementations meant to be completed in a subclass.
You are certainly free to write your own default methods on your interfaces. And certainly you should do so if you are in a similar situation of having published an interface that others may have implemented, and now you want to add methods. But unnecessarily adding default methods is likely to confuse other programmers who expect partial implementations on an abstract class rather than an interface.
Four situations calling for default method on an interface
In that same post linked above, Brian Goetz suggests three other cases beyond interface evolution where default methods on an interface may be appropriate. Here is a quick mention; see his post for details.
Optional methods - The default method throws an UnsupportedOperationException because we expect implementations of this interface to more often not want to implement this method.
Convenience methods
Combinators
Start with interface, move to abstract class for shared code
As for choosing between an interface and abstract class:
Generally start with an interface. Or several interfaces if you want various implementing classes to mix various contracts (see mixin).
Think twice before adding a default method. Consider if your situation meets one of the four cases recommended by Brian Goetz as discussed above.
If you come to realize that you have duplicated code across multiple classes, then consider centralizing that shared code to an abstract class to be used across subclasses.
Alternatively, use composition rather than inheritance (discussed below).
For example, you might have a class for domestic ShippingLabelUS as well as ShippingLabelCanada and ShippingLabelOverseas. All three need to convert between imperial pounds and metric kilograms. You find yourself copying that code between the classes. At this point you might consider having all three classes extend from abstract class ShippingLabel where a single copy of the weight conversion methods live.
While designing your API keep in mind that Java, like most OOP languages, has single-inheritance. So your subclasses are limited to extending only one class. To be a bit more specific about the single-versus-multiple inheritance, I will quote Brian Goetz from this PDF of a slide deck:
[regarding default methods on an interface]
Wait,is this multiple inheritance in Java?
• Java always had multiple inheritance of types
• This adds multiple inheritance of behavior
• But not of state, where most of the trouble comes from
Composition over inheritance
An alternative to using an abstract class for shared behavior is creating a separate class for specific behavior, then adding an object of that separate class to be kept as a member field on the larger class. Wise programmers often share this pearl of wisdom: Prefer composition over inheritance.
Regarding the shipping label example above, you could create a WeightConverter class, an object of which would be a member of each of the three label classes. In this arrangement, no need for the abstract class.
I've seen in several code libraries classes named Mixin with comments like:
//Mixin style implementation
public class DetachableMixin implements Detachable {}
Which is the concept under this style of implementations?
Here is a qoute from Joshua Bloch "Efective Java" (I don't think, I could explain it better myself):
Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type
that a class can implement in addition to its “primary type” to declare that it provides
some optional behavior. For example, Comparable is a mixin interface that
allows a class to declare that its instances are ordered with respect to other mutually
comparable objects. Such an interface is called a mixin because it allows the
optional functionality to be “mixed in” to the type’s primary functionality.
Abstract classes can’t be used to define mixins for the same reason that they can’t
be retrofitted onto existing classes: a class cannot have more than one parent, and
there is no reasonable place in the class hierarchy to insert a mixin.
The other answer is spot on, but it might be worth pointing out that other JVM languages go even further.
Scala for examples has traits - basically "interfaces" with method implementations. In scala, you can mix one class together with multiple traits, thereby allowing to inherit behavior from several different "places.
Basically the same concept that Java picked up with Java 8, where you know can add default method behavior to interfaces. And for the record: if I recall it correctly, Java8 interfaces and default methods are not meant to introduce a full "mixin" concept in the Java language. The idea is not that you should use this feature to achieve multiple inheritance through the back door. See this lengthy answer from Stuart Mark, one of the people driving the Java language evolution. They state:
The purpose of default methods ... is to enable interfaces to be evolved in a compatible manner after their initial publication.
A good article about implementing mixin pattern with Virtual Extension Methods since Java 8: https://kerflyn.wordpress.com/2012/07/09/java-8-now-you-have-mixins/
The virtual extension method is something new in Java. It brings another mean of expression to create new patterns and best pratices. This article provides an example of such a pattern, enabled in Java 8 due to the use of virtual extension methods. I am sure you can extract other new patterns from them. But, as I have experienced here, you should not hesitate to share them in a view to check their validaty.
To develop a fully functional application consisting of more than 4 classes, what is the right way of handling shared data? I have researched about Static Methods and variables and Utility classes. It's said that use of Static methods hinders the concept of Object Orientation concept. So, if anybody could help me on how to use shared data between classes without hindering Object Oriented concept, then I would be highly grateful.
There are two primary axes of "inheritance" in object-oriented languages like Java. "Implementation" inheritance is where the sub-class inherits the actual code implementation from the parent. "Interface" inheritance is where the "sub-class" adheres to the public interface of the "parent".
Alas, Java actually mixes the two notions together a bit... Java interfaces are nice and clean -- when you "implement" an interface, you are stipulating that your class adheres to the "contract" of the interface that you specified. Java class inheritance isn't so clean -- when you sub-class in Java you are getting both the code inheritance but you are also stipulating that your sub-class adheres to the "contract" of the interface of the parent class.
Abstract classes in Java are just like regular Java classes but with the added constraint that you cannot instantiate them directly. In terms of that added constraint, they are basically classes which don't actually implement all of the code specified by their "contract".
So, it's generally considered good OO practice to specify the "contract" which you want to adhere to via Java interfaces. Then use normal Java class inheritance primarily for code reuse purposes. Use abstract Java classes when you want to provide some standard base code but want/need to force the user's of your class to complete the implementation (i.e., you create a skeleton implementation and the sub-classes must flesh it out).
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 9 years ago.
I want to solidify my understanding of the "coding to interface" concept. As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes. To use the interface one can simply call the methods on an instance of the concrete class.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Based on the above:
Are there any fallacies in my understanding of "coding to interfaces"?
Are there any benefits of coding to interfaces that I missed?
Thanks.
Just one possible correction:
To use the interface one can simply call the methods on an instance of the concrete class.
One would call the methods on a reference of the type interface, which happens to use the concrete class as implementation:
List<String> l = new ArrayList<String>();
l.add("foo");
l.add("bar");
If you decided to switch to another List implementation, the client code works without change:
List<String> l = new LinkedList<String>();
This is especially useful for hiding implementation details, auto generating proxies, etc.
You'll find that frameworks like spring and guice encourage programming to an interface. It's the basis for ideas like aspect-oriented programming, auto generated proxies for transaction management, etc.
Your understanding seems to be right on. Your co-worker just swung by your desk and has all the latest pics of the christmas party starring your drunk boss loaded onto his thumbdrive. Your co-worker and you do not think twice about how this thumbdrive works, to you its a black box but you know it works because of the USB interface.
It doesn't matter whether it's a SanDisk or a Titanium (not even sure that is a brand), size / color don't matter either. In fact, the only thing that matters is that it is not broken (readable) and that it plugs into USB.
Your USB thumbdrive abides by a contract, it is essentially an interface. One can assume it fulfills some very basic duties:
Plugs into USB
Abides by the contract method CopyDataTo:
public Interface IUSB {
void CopyDataTo(string somePath); //used to copy data from the thumbnail drive to...
}
Abides by the contract method CopyDataFrom:
public Interface IUSB {
void CopyDataFrom(); //used to copy data from your PC to the thumbnail drive
}
Ok maybe not those methods but the IUSB interface is just a contract that the thumbnail drive vendors have to abide by to ensure functionality across various platforms / vendors. So SanDisk makes their thumbdrive by the interface:
public class SanDiskUSB : IUSB
{
//todo: define methods of the interface here
}
Ari, I think you already have a solid understanding (from what it sounds like) about how interfaces work.
The main advantage is that the use of an interface loosely couples a class with it's dependencies. You can then change a class, or implement a new concrete interface implementation without ever having to change the classes which depend on it.
To use the interface one can simply call the methods on an instance of the concrete class.
Typically you would have a variable typed to the interface type, thus allowing only access to the methods defined in the interface.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Sort of. Most importantly, it allows you to write APIs that take parameters with interface types. Users of the API can then pass in their own classes (which implement those interfaces) and you code will work on those classes even though they didn't exist yet when it was written (such as java.util.Arrays.sort() being able to sort anything that implements Comparable or comes with a suitable Comparator).
From a design perspective, interfaces allow/enforce a clear separation between API contracts and implementation details.
The aim of coding against interfaces is to decouple your code from the concrete implementation in use. That is, your code will not make assumptions about the concrete type, only the interface. Consequently, the concrete implementation can be exchanged without needing to adjust your code.
You didn't list the part about how you get an implementation of the interface, which is important. If you explicitly instantiate the implementing class with a constructor then your code is tied to that implementation. You can use a factory to get an instance for you but then you're as tied to the factory as you were before to the implementing class. Your third alternative is to use dependency injection, which is having a factory plug the implementing object into the object that uses it, in which case you escape having the class that uses the object being tied to the implementing class or to a factory.
I think you may have hinted at this, but I believe one of the biggest benefits of coding to an interface is that you are breaking dependency on concrete implementation. You can achieve loose coupling and make it easier to switch out specific implementations without changing much code. If you are just learning, I would take a look at various design patterns and how they solve problems by coding to interfaces. Reading the book Head First: Design Patterns really helped things click for me.
As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes.
The only sort of mutation i see in your thinking is this - You're going to call out expected contracts, not expected functionality. The functionality is implemented in the concrete classes. The interface only states that you will be able to call something that implements the interface with the expected method signatures. Functionality is hidden from the calling object.
This will allow you to stretch your thinking into polymorphism as follows.
SoundMaker sm = new Duck();<br/>
SoundMaker sm1 = new ThunderousCloud();
sm.makeSound(); // quack, calls all sorts of stuff like larynx, etc.<br/>
sm1.makeSound(); // BOOM!, completely different operations here...
I will choose Java as an example, most people know it, though every other OO language was working as well.
Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.
However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.
Now there was this article, saying it's better to inherit interfaces than implementations, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the fragile base class problem. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.
What bugs me about this, is that implementation inheritance means code reuse, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?
E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.
How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?
Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.
Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like
public void move() {
abstractCarObject.move();
}
?
Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?
Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. )
Long answer:
Well, inheritance is not actually for "code re-use", it is for class "specialization", I think this is a misinterpretation.
For instance is it a very bad idea to create a Stack from a Vector, just because they are alike. Or properties from HashTable just because they store values. See [Effective].
The "code reuse" was more a "business view" of the OO characteristics, meaning that you objects were easily distributable among nodes; and were portable and didn't not have the problems of previous programming languages generation. This has been proved half rigth. We now have libraries that can be easily distributed; for instance in java the jar files can be used in any project saving thousands of hours of development. OO still has some problems with portability and things like that, that is the reason now WebServices are so popular ( as before it was CORBA ) but that's another thread.
This is one aspect of "code reuse". The other is effectively, the one that has to do with programming. But in this case is not just to "save" lines of code and creating fragile monsters, but designing with inheritance in mind. This is the item 17 in the book previously mentioned; Item 17: Design and document for inheritance or else prohibit it. See [Effective]
Of course you may have a Car class and tons of subclasses. And yes, the approach you mention about Car interface, AbstractCar and CarImplementation is a correct way to go.
You define the "contract" the Car should adhere and say these are the methods I would expect to have when talking about cars. The abstract car that has the base functionality that every car but leaving and documenting the methods the subclasses are responsible to handle. In java you do this by marking the method as abstract.
When you proceed this way, there is not a problem with the "fragile" class ( or at least the designer is conscious or the threat ) and the subclasses do complete only those parts the designer allow them.
Inheritance is more to "specialize" the classes, in the same fashion a Truck is an specialized version of Car, and MosterTruck an specialized version of Truck.
It does not make sanse to create a "ComputerMouse" subclase from a Car just because it has a Wheel ( scroll wheel ) like a car, it moves, and has a wheel below just to save lines of code. It belongs to a different domain, and it will be used for other purposes.
The way to prevent "implementation" inheritance is in the programming language since the beginning, you should use the final keyword on the class declaration and this way you are prohibiting subclasses.
Subclassing is not evil if it's done on purpose. If it's done uncarefully it may become a nightmare. I would say that you should start as private and "final" as possible and if needed make things more public and extend-able. This is also widely explained in the presentation"How to design good API's and why it matters" See [Good API]
Keep reading articles and with time and practice ( and a lot of patience ) this thing will come clearer. Although sometime you just need to do the work and copy/paste some code :P . This is ok, as long you try to do it well first.
Here are the references both from Joshua Bloch ( formerly working in Sun at the core of java now working for Google )
[Effective]
Effective Java. Definitely the best java book a non beginner should learn, understand and practice. A must have.
Effective Java
[Good API]Presentation that talks on API's design, reusability and related topics.
It is a little lengthy but it worth every minute.
How To Design A Good API and Why it Matters
Regards.
Update: Take a look at minute 42 of the video link I sent you. It talks about this topic:
"When you have two classes in a public API and you think to make one a subclass of another, like Foo is a subclass of Bar, ask your self , is Every Foo a Bar?... "
And in the minute previous it talks about "code reuse" while talking about TimeTask.
The problem with most example against inheritance are examples where the person is using inheritance incorrectly, not a failure of inheritance to correctly abstract.
In the article you posted a link to, the author shows the "brokenness" of inheritance using Stack and ArrayList. The example is flawed because a Stack is not an ArrayList and therefore inheritance should not be used. The example is as flawed as String extending Character, or PointXY extending Number.
Before you extend class, you should always perform the "is_a" test. Since you can't say Every Stack is an ArrayList without being wrong in some way, then you should not inheirit.
The contract for Stack is different than the contract for ArrayList (or List) and stack should not be inheriting methods that is does not care about (like get(int i) and add()). In fact Stack should be an interface with methods such as:
interface Stack<T> {
public void push(T object);
public T pop();
public void clear();
public int size();
}
A class like ArrayListStack might implement the Stack interface, and in that case use composition (having an internal ArrayList) and not inheritance.
Inheritance is not bad, bad inheritance is bad.
You could also use composition and the strategy pattern.link text
public class Car
{
private ICar _car;
public void Move() {
_car.Move();
}
}
This is far more flexible than using inheritance based behaviour as it allows you to change at runtime, by substituting new Car types as required.
You can use composition. In your example, a Car object might contain another object called Drivetrain. The car's move() method could simply call the drive() method of it's drivetrain. The Drivetrain class could, in turn, contain objects like Engine, Transmission, Wheels, etc. If you structured your class hierarchy this way, you could easily create cars which move in different ways by composing them of different combinations of the simpler parts (i.e. reuse code).
To make mixins/composition easier, take a look at my Annotations and Annotation Processor:
http://code.google.com/p/javadude/wiki/Annotations
In particular, the mixins example:
http://code.google.com/p/javadude/wiki/AnnotationsMixinExample
Note that it doesn't currently work if the interfaces/types being delegated to have parameterized methods (or parameterized types on the methods). I'm working on that...
It's funny to answer my own question, but here's something I found that is pretty interesting: Sather.
It's a programming language with no implementation inheritance at all! It knows interfaces (called abstract classes with no implementation or encapsulated data), and interfaces can inherit of each other (actually they even support multiple inheritance!), but a class can only implement interfaces (abstract classes, as many as it likes), it can't inherit from another class. It can however "include" another class. This is rather a delegate concept. Included classes must be instantiated in the constructor of your class and are destroyed when your class is destroyed. Unless you overwrite the methods they have, your class inherits their interface as well, but not their code. Instead methods are created that just forward calls to your method to the equally named method of the included object. The difference between included objects and just encapsulated objects is that you don't have to create the delegation forwards yourself and they don't exist as independent objects that you can pass around, they are part of your object and live and die together with your object (or more technically spoken: The memory for your object and all included ones is created with a single alloc call, same memory block, you just need to init them in your constructor call, while when using real delegates, each of these objects causes an own alloc call, has an own memory block, and lives completely independently of your object).
The language is not so beautiful, but I love the idea behind it :-)
Inheritance is not necessary for an object oriented language.
Consider Javascript, which is even more object-oriented than Java, arguably. There are no classes, just objects. Code is reused by adding existing methods to an object. A Javascript object is essentially a map of names to functions (and data), where the initial contents of the map is established by a prototype, and new entries can be added to a given instance on the fly.
You should read Design Patterns. You will find that Interfaces are critical to many types of useful Design Patterns. For example abstracting different types of network protocols will have the same interface (to the software calling it) but little code reuse because of different behaviors of each type of protocol.
For some algorithms are eye opening in showing how to put together the myriad elements of a programming to do some useful task. Design Patterns do the same for objects.Shows you how to combine objects in a way to perform a useful task.
Design Patterns by the Gang of Four