Oo programming why use interfaces




















Because if we create a superclass named Distraction , and both the Facebook class and AdventureLoverFriend class extend it, we can collect all distractable things in one list. Because we can refer to the subclass object with the superclass reference variable, we can conduct the needed operation on this list.

This is because, in Java, one class cannot extend more than one class. At this time, we can see how the interface is useful. As you can see, the interfaces allow us to define common behavior that can be implemented by any class, regardless of its inheritance. Although the AdventureLoverFriend class extends the Friend class and the Facebook class extends the MobileApplication class, we can add common distractable behavior to them by implementing the Distractable interface.

Since Java allows us to refer implementation class objects with interface reference variable, we can write the following in the ExamPreparation class:. Also, consider that we only focus on common distractable behavior in the printList method. We can show it like this in the code:. This occurs at "program time". When the vehicle. This occurs at "run time". They require the programmer to create specific functions that are expected in an implementing class when it implements an Interface.

Again, this allows all objects in a "set" of like objects to be treated based on the "high level" type of the set, rather than on the specific type of the individual object. Interfaces An interface is a description of the actions that an object can do The syntax of an Interface An interface has a very simple syntax that looks very much like a class definition Implementing an Interface To tell the computer that a new class that you are writing will fulfill all the requirements implement all the functions of an interface, you must use the keyword implements in the same location where you can use the keyword extends.

Here is an example of a Car Class which implements the Vehicle definition. Polymorphism applied to Interfaces What is the power of the interface? Normally we would have to create separate vehicles. Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler.

If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. All rights reserved. Behavior used in this sense is truly just a non-technical word for abstract methods. An abstract method is a method which does not, in fact cannot, contain a method body :.

The natural reaction for me, and a number of individuals whom I have tutored, after first looking at an interface , was to wonder what the utility of sharing only a return type , method name , and parameter list might be.

On the surface, it looks like a great way to create extra work for yourself, or whoever else might be writing the class which implements the interface.

The answer, is that interfaces are perfect for situations where you want a set of classes to behave in the same manner i.

To take a simple but relevant example, the Android platform possesses two classes which are primarily in the business of creating and managing part of the user interface: Activity and Fragment. It follows that these classes will very often have the requirement of listening to events which pop up when a widget is clicked or otherwise interacted with by a user. Not only would making our Activities and Fragments inherit from OnClickManager make it impossible to handle events in a different manner, but the kicker is that we could not even do that if we wanted to.

Both Activity and Fragment already extend a parent class , and Java does not allow multiple parent classes. So our problem is that we want a set of classes to behave the same way, but we must have flexibility on how the class implements that behavior. This brings us back to the earlier example of the View. OnClickListener :. This is the actual source code which is nested in the View class , and these few lines allow us to ensure consistent behavior across different widgets Views and UI controllers Activities, Fragments, etc.

I have hopefully answered the general question about why interfaces exist in Java; among many other languages. From one perspective, they are just a means of sharing code between classes, but they are deliberately less detailed in order to allow for different implementations.

But just as inheritance can be used both as a mechanism for sharing code and abstraction albeit with restrictions on class hierarchy , it follows that interfaces provide a more flexible mechanism for abstraction.

To recap, the basic idea is that you will want to use screws in situations where changing the existing structure which can be a result of fixing mistakes, design changes, and so forth is likely to happen. Nails are fine to use when you just need to fasten parts of the structure together and are not particularly worried about taking them apart in the near future.

Nails and screws are meant to be analogous to concrete and abstract references the term dependencies also applies between classes. Just so there is no confusion, the following sample will demonstrate what I mean:.

Here, we have a class called Client which possesses two kinds of references. Notice that, assuming Client does not have anything to do with creating its references it really should not , it is decoupled from the implementation details of any particular network adapter.

There are a few important implications of this loose coupling. Imagine for a moment that you are working in a team of two developers; one to build the front end, one to build the back end.

As long as both developers are kept aware of the interfaces which couple their respective classes together, they can carry on with the work virtually independently of one another. This is very easy with interfaces; just build a Test Double which implements the appropriate interface :. In principle, what can be observed is that working with abstract references opens the door to increased modularity, testability, and some very powerful design patterns such as the Facade Pattern , Observer Pattern , and more.

They can also allow developers to find a happy balance of designing different parts of a system based on behavior Program To An Interface , without getting bogged down in implementation details. Abstractions do not exist in the same way as a concrete thing. This is reflected in the Java Programming language by the fact that abstract classes and interfaces may not be instantiated.

In fact, the idea of expecting an unimplemented interface or abstract class to function at runtime makes as much sense as expecting a UPS uniform to float around delivering packages.

Something concrete must be behind the abstraction for it to be of utility; even if the calling class does not need to know what is actually behind abstract references. If you have made it this far, then I am happy to tell you that I have no more philosophical tangents or jargon phrases to translate. Simply put, abstract classes are a mechanism for sharing implementation and behavior across a set of classes.

Now, I will admit straight away that I do not find myself using abstract classes all that often. Even so, my hope is that by the end of this section you will know exactly when they are called for. Roughly a year into building Android apps in Java, I was rebuilding my first Android app from scratch.

The first version was the kind of horrendous mass of code that you would expect from a self-taught developer with little guidance. By the time I wanted to add new functionality, it became clear that the tightly coupled structure I had built exclusively with nails , was so impossible to maintain that I must rebuild it entirely.

The app was a workout log that was designed to allow easy recording of your workouts, and the ability to output the data of a past workout as a text or image file. Without getting into too much detail, I structured the data models of the app such that there was a Workout object, which comprised of a collection of Exercise objects among other fields which are irrelevant to this discussion. As I was implementing the feature for outputting workout data to some kind of visual medium, I realized that I had to deal with a problem: Different kinds of exercises would require different kinds of text outputs.

To give you a rough idea, I wanted to change the outputs depending on the type of exercise like so:.



0コメント

  • 1000 / 1000