Is there any true point to the Java interface? [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How are Java interfaces actually used?
I'm not talking from an accademic buzzword point of view but from a pratical developer point of view.
So taking the example:-
Class1 implements Interface
public String methodOne() {
return "This is Class1.methodOne()";
}
public String methodTwo() {
return "This is Class1.methodTwo()";
}
}
Class2:
Class2 implements Interface
public String methodOne() {
return "This is Class2.methodOne()";
}
public String methodTwo() {
return "This is Class2.methodTwo()";
}
}
Using the Interface:-
Client {
Interface intface = new Class1();
intface.methodOne();
intface.methodTwo();
Interface intface = new Class2();
intface.methodOne();
intface.methodTwo();
}
But what are the benefits over just writting:-
Client {
Class1 clas1 = new Class1();
clas1.methodOne();
clas1.methodTwo();
Class2 clas2 = new Class2();
clas2.methodOne();
clas2.methodTwo();
}
And bypass the Interface altogether.
Interfaces just seem to be an additional layer of code for the sake of an additional layer of code,
or is there more to them than just "Here are the methods that the class you are accessing has"?

When using standalone classes, you don't need interfaces. However, when you have a type hierarchy, interfaces are indeed indispensable.
Your simple example does not really do justice, but let's rename your interface to something more useful and concrete, e.g. a Sorter algorithm which can take a list of items and sort them. You can have several different sorting algorithms implemented, and you may want to change the algorithm used, based on the context (i.e. QuickSort is faster for large data sets, but BubbleSort is better for small data sets, etc.) So you don't want to tie the client code to one specific algorithm. By using the polymorphic Sorter type (implemented as an interface), you can pass different concrete sorter objects to the client, without it knowing (and caring) what algorithm it is actually using. And you can any time introduce a better sorting algorithm, or remove one which proved inefficient, without the clients noticing anything.
Such a feat would be impossible without interfaces. The alternative would be calling the sort method of choice directly from (possibly duplicated) if-else or switch blocks all over the place, with the inevitable possibility of introducing bugs when forgetting to update all places properly when a sorting algorithm is added/removed... not to mention that you would need to recompile all client code after each such change :-(

Suppose you want a collection of objects with both methods "Method1" and "Method2".
And you don't want to programatically check each instance in the collection for its type.
A collection of objects the implement that interface saves you from doing this.
It calls Polymorphism and it is very useful.

The other folks have pretty much covered your question but, in a word: Yes!
The Java language was actually conceived as a fairly minimal object-oriented language, and interfaces were there from the very beginning. There are concepts of describing the relationships between classes that are hard or impossible to do without either interfaces or some performance-costly runtime type identification. All or almost all the patterns quoted in the famous Design Patterns book (here's the book itself) rely on interfaces.

(Not sure how I respond without it being seen as an answer but...)
Wow, so many answers so quickly, pretty impressive forum - cheers! :-D
So would it be reasonable to say that an Interface essentially sets the 'rules' for which the concrete classes must meet?
For example if I had classes Class1 & Class2, both of which have method 'getList()'.
Without implementing an Interface Class1.getList() could return say a list of Strings and Class2.getList() could return Integers.
Essentially the Interface sets the rules that my Class has to have a method of getList() and that method must return List,
so if both implement the Interface Lister with method 'public String getList();' I know that both Class1 & Class2 getList() returns a
List of types String.
But concrete Class1 could be returning a list of departments whereas Class2 is a list of employees, but I know they both return a list of Strings.
This would probably become more useful if I had maybe half dozen or so classes each with half dozen methods all of which I want to
ensure meet the .getList returns a list of type String 'rule'.

I use interfaces mostly for
simulating multiple inheritance
defining a service contract and a service implementation
single method callback contracts
and because
some dependency injection frameworks require interfaces to work
mocking interfaces easier than mocking classes
many AOP frameworks work better with interfaces than classes
And it is not really a layer of code between a service and its client, but more a formal contract.

Interfaces are useful if there is a chance that you'll need more than one implementation, maybe for another technology (different database) or for testing.

Interfaces define the contract of the type, without anu implementation details. This lets you program against the interface without knowing the actual implementation class.
An example of the advantage of interfaces using your code could be:
public void useInterface(Interface obj) {
obj.methodOne();
obj.methodTwo();
}
and calling it as in:
useInterface(new Class1());
useInterface(new Class2());
The Java collections classes make heavy use of interfaces, it allows you to switch implementations for lists and maps later without having to change the code using those instances.

Consider the following method which receives a list of 'intfaces', you don't have to know if you handle clas1 or clas2, you just want to handle something that 'is a' intface. You may add clas3 implement intface later on and it will stil work...
public void callMethods(List<intface> intfaces){
for(Interface intface : intfaces) {
intface.methodOne();
intface.methodTwo();
}
}

Related

What is use of assaigning subclass object to superclass reference variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
I keep coming across this term:
Program to an interface.
What exactly does it mean? A real life design scenario would be highly appreciated.
To put it simply, instead of writing your classes in a way that says
I depend on this specific class to do my work
you write it in a way that says
I depend on any class that does this stuff to do my work.
The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.
The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.
As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.
If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.
An interface is a collection of related methods, that only contains the signatures of those methods - not the actual implementation.
If a class implements an interface (class Car implements IDrivable) it has to provide code for all signatures defined in the interface.
Basic example:
You have to classes Car and Bike. Both implement the interface IDrivable:
interface IDrivable
{
void accelerate();
void brake();
}
class Car implements IDrivable
{
void accelerate()
{ System.out.println("Vroom"); }
void brake()
{ System.out.println("Queeeeek");}
}
class Bike implements IDrivable
{
void accelerate()
{ System.out.println("Rattle, Rattle, ..."); }
void brake()
{ System.out.println("..."); }
}
Now let's assume you have a collection of objects, that are all "drivable" (their classes all implement IDrivable):
List<IDrivable> vehicleList = new ArrayList<IDrivable>();
list.add(new Car());
list.add(new Car());
list.add(new Bike());
list.add(new Car());
list.add(new Bike());
list.add(new Bike());
If you now want to loop over that collection, you can rely on the fact, that every object in that collection implements accelerate():
for(IDrivable vehicle: vehicleList)
{
vehicle.accelerate(); //this could be a bike or a car, or anything that implements IDrivable
}
By calling that interface method you are not programming to an implementation but to an interface - a contract that ensures that the call target implements a certain functionality.
The same behavior could be achieved using inheritance, but deriving from a common base class results in tight coupling which can be avoided using interfaces.
Polymorphism depends on programming to an interface, not an implementation.
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to this principle of programming to an interface.
See the Factory Method pattern for further reasoning of this design.
Source: "Design Patterns: Elements of Reusable Object-Oriented Software" by G.O.F.
Also See: Factory Pattern. When to use factory methods?
Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection. However, each JDBC driver provides its own implementation of Connection. You don't have to know anything about the particular implementation, because it conforms to the Connection interface.
Another one is from the java collections framework. There is a java.util.Collection interface, which defines size, add and remove methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList because it's more efficient for it's purposes, and the other uses a TreeSet.
Because both LinkedList and TreeSet implement the Collection interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size() method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection interface, rather than to LinkedList and TreeSet in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.
Every object has an exposed interface. A collection has Add, Remove, At, etc. A socket may have Send, Receive, Close and so on.
Every object you can actually get a reference to has a concrete implementation of these interfaces.
Both of these things are obvious, however what is somewhat less obvious...
Your code shouldn't rely on the implementation details of an object, just its published interface.
If you take it to an extreme, you'd only code against Collection<T> and so on (rather than ArrayList<T>). More practically, just make sure you could swap in something conceptually identical without breaking your code.
To hammer out the Collection<T> example: you have a collection of something, you're actually using ArrayList<T> because why not. You should make sure you're code isn't going to break if, say, you end up using LinkedList<T> in the future.
"Programming to an interface" happens when you use libraries, other code you depend upon in your own code. Then, the way that other code represents itself to you, the method names, its parameters, return values etc make up the interface you have to program to. So it's about how you use third-party code.
It also means, you don't have to care about the internals of the code you depend on, as long as the interface stays the same, your code is safe (well, more or less...)
Technically there are finer details, like language concepts called "interfaces" in Java for example.
If you want to find out more, you could ask what "Implementing an Interface" means...
I think this is one of Erich Gamma's mantras. I can't find the first time he described it (before the GOF book), but you can see it discussed in an interview at: http://www.artima.com/lejava/articles/designprinciples.html
It basically means that the only part of the library which you're going to use you should rely upon is it's API (Application programming interface) and that you shouldn't base your application on the concrete implementation of the library.
eg. Supposed you have a library that gives you a stack. The class gives you a couple of methods. Let's say push, pop, isempty and top. You should write your application relying only on these. One way to violate this would be to peek inside and find out that the stack is implemented using an array of some kind so that if you pop from an empty stack, you'd get some kind of Index exception and to then catch this rather than to rely on the isempty method which the class provides. The former approach would fail if the library provider switched from using an array to using some kind of list while the latter would still work assuming that the provider kept his API still working.

Using interfaces as class members [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
I keep coming across this term:
Program to an interface.
What exactly does it mean? A real life design scenario would be highly appreciated.
To put it simply, instead of writing your classes in a way that says
I depend on this specific class to do my work
you write it in a way that says
I depend on any class that does this stuff to do my work.
The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.
The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.
As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.
If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.
An interface is a collection of related methods, that only contains the signatures of those methods - not the actual implementation.
If a class implements an interface (class Car implements IDrivable) it has to provide code for all signatures defined in the interface.
Basic example:
You have to classes Car and Bike. Both implement the interface IDrivable:
interface IDrivable
{
void accelerate();
void brake();
}
class Car implements IDrivable
{
void accelerate()
{ System.out.println("Vroom"); }
void brake()
{ System.out.println("Queeeeek");}
}
class Bike implements IDrivable
{
void accelerate()
{ System.out.println("Rattle, Rattle, ..."); }
void brake()
{ System.out.println("..."); }
}
Now let's assume you have a collection of objects, that are all "drivable" (their classes all implement IDrivable):
List<IDrivable> vehicleList = new ArrayList<IDrivable>();
list.add(new Car());
list.add(new Car());
list.add(new Bike());
list.add(new Car());
list.add(new Bike());
list.add(new Bike());
If you now want to loop over that collection, you can rely on the fact, that every object in that collection implements accelerate():
for(IDrivable vehicle: vehicleList)
{
vehicle.accelerate(); //this could be a bike or a car, or anything that implements IDrivable
}
By calling that interface method you are not programming to an implementation but to an interface - a contract that ensures that the call target implements a certain functionality.
The same behavior could be achieved using inheritance, but deriving from a common base class results in tight coupling which can be avoided using interfaces.
Polymorphism depends on programming to an interface, not an implementation.
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to this principle of programming to an interface.
See the Factory Method pattern for further reasoning of this design.
Source: "Design Patterns: Elements of Reusable Object-Oriented Software" by G.O.F.
Also See: Factory Pattern. When to use factory methods?
Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection. However, each JDBC driver provides its own implementation of Connection. You don't have to know anything about the particular implementation, because it conforms to the Connection interface.
Another one is from the java collections framework. There is a java.util.Collection interface, which defines size, add and remove methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList because it's more efficient for it's purposes, and the other uses a TreeSet.
Because both LinkedList and TreeSet implement the Collection interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size() method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection interface, rather than to LinkedList and TreeSet in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.
Every object has an exposed interface. A collection has Add, Remove, At, etc. A socket may have Send, Receive, Close and so on.
Every object you can actually get a reference to has a concrete implementation of these interfaces.
Both of these things are obvious, however what is somewhat less obvious...
Your code shouldn't rely on the implementation details of an object, just its published interface.
If you take it to an extreme, you'd only code against Collection<T> and so on (rather than ArrayList<T>). More practically, just make sure you could swap in something conceptually identical without breaking your code.
To hammer out the Collection<T> example: you have a collection of something, you're actually using ArrayList<T> because why not. You should make sure you're code isn't going to break if, say, you end up using LinkedList<T> in the future.
"Programming to an interface" happens when you use libraries, other code you depend upon in your own code. Then, the way that other code represents itself to you, the method names, its parameters, return values etc make up the interface you have to program to. So it's about how you use third-party code.
It also means, you don't have to care about the internals of the code you depend on, as long as the interface stays the same, your code is safe (well, more or less...)
Technically there are finer details, like language concepts called "interfaces" in Java for example.
If you want to find out more, you could ask what "Implementing an Interface" means...
I think this is one of Erich Gamma's mantras. I can't find the first time he described it (before the GOF book), but you can see it discussed in an interview at: http://www.artima.com/lejava/articles/designprinciples.html
It basically means that the only part of the library which you're going to use you should rely upon is it's API (Application programming interface) and that you shouldn't base your application on the concrete implementation of the library.
eg. Supposed you have a library that gives you a stack. The class gives you a couple of methods. Let's say push, pop, isempty and top. You should write your application relying only on these. One way to violate this would be to peek inside and find out that the stack is implemented using an array of some kind so that if you pop from an empty stack, you'd get some kind of Index exception and to then catch this rather than to rely on the isempty method which the class provides. The former approach would fail if the library provider switched from using an array to using some kind of list while the latter would still work assuming that the provider kept his API still working.

What is the advantage of using interfaces [duplicate]

This question already has answers here:
Interfaces in Java - what are they for? [duplicate]
(9 answers)
Closed 9 years ago.
Let's say you have an interface
public interface Change {
void updateUser();
void deleteUser();
void helpUser();
}
I've read that interfaces are Java's way to implement multiple inheritance. You implement an interface, then you have access to its methods. What I don't understand is, the methods don't have any body in the interface, so you need to give them a body in your class. So if you an interface is implemented by more than one class, you need to give the method a body in more than one class. Why is this better than just having individual methods in your classes, and not implementing an interface?
My professor in college once gave a great anecdote to describe polymorphism and encapsulation. It went like this.
Does anyone here know how a soda machine works? (Cue confused glances about why we'd even talk about this.) No? Let me tell you.
You drop in your change, and inside the machine is a little monkey who counts all your change to make sure you put in enough money. When you press the button for your soda, a little light comes on telling the monkey which button you pressed, and if you entered the right amount of change, he grabs your choice and throws it into the little hole for you to grab your soda.
This is the concept of encapsulation. We hide the implementation of the soda machine. Unless it's got one of those fancy, clear windows to let you see the inside, you honestly have no idea how it really works. All you know is that you put in some cash, you press a button, and if you put in enough, you get your drink.
To add to that, you know how to use a soda machine's interface, so therefore as long as the machine's interface follows the usual soda machine interface, you can use it. This is called the interface contract. The machine can be bringing the drinks from Antarctica on a conveyor belt for all you care, as long as you get your drink, it's cold, and you get change back.
Polymorphism is the idea that when you use the soda machine interface, it could be doing different things. This is why encapsulation and polymorphism are closely related. In polymorphism, all you know is that you're using a SodaMachine implementation, which can be changed, and as a result, different things can be done behind the scenes. This leads to the driving concept of polymorphism, which is the ability of one object, the SodaMachine, to actually act as both a MonkeySodaMachine and a ConveyorSodaMachine depending on the machine actually behind the interface.
Probably not word-for-word, but close enough. Essentially it boils down to two concepts: polymorphism and encapsulation. Let me know if you want clarification.
Why is this better than just having individual methods in your classes, and not implementing an interface?
Because if a class C implements an interface I, you can use a C whenever an I is expected. If you do not implement the interface, you could not do this (even if you provided all of the appropriate methods as mandated by the interface):
interface I {
void foo();
}
class C1 implements I {
public void foo() {
System.out.println("C1");
}
}
class C2 { // C2 has a 'foo' method, but does not implement I
public void foo() {
System.out.println("C2");
}
}
...
class Test {
public static void main(String[] args) {
I eye1 = new C1(); // works
I eye2 = new C2(); // error!
}
}
It separates what the caller expects from the implementation. You have a pure set of methods you can call without any knowledge of the implementation. In fact some libraries like JMS and JDBC provide interfaces without any implementations.
This separation means you don't need to know the class of any actual implementation.
An interface allows you to guarantee that certain methods exist and return the required types. When the compiler knows this, it can use that assumption to work with unknown classes as if they had certain known behavior. For example, the comparable interface guarantees that an implementing class will be able to compareTo() some similar object and will return an int.
This means that you can compare anything that implements this interface - so you can sort anything that is Comparable instead of writing one method to sort Strings and another to sort Integers and another to sort LabelledBoxesOfBooks
The interface essentially guarentees that all the methods that inherit it will have its methods, so that you can safely call a method in the interface for anything that inherits it.
It makes it easier to define APIs using interfaces, so that all concrete implementations of the interfaces provide the expected methods in each class.
It also provides a way to implement multiple inheritance, which is not possible (in Java) with straight class inheritance.

The importance of interfaces in Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Let's say we have two classes, Tiger and Aeroplane.
One thing in common for these two types is the Speed. I know that it would be illogical to create a superclass ClassWithSpeed and then derive subclasses Aeroplane and Tiger from it.
Instead, it is better to create an interface that contains the method speed() and then implement it in Aeroplane and Tiger. I get that. But, we can do the same thing without interfaces. We could define method speed() in Aeroplane and method speed() in Tiger.
The only (maybe very big) flaw it would be that we couldn't "reach" the objects of Tiger and Aeroplane through an interface reference.
I am beginner in Java and OOP, and I would be very grateful if someone explained to me the role of interfaces.
Cheers!
It's:
public int howFast(Airplane airplane) {
return airplane.speed();
}
public int howFast(Tiger tiger) {
return tiger.speed();
}
public int howFast(Rocket rocket) {
return rocket.speed();
}
public int howFast(ThingThatHasntBeenInventedYet thingx) {
// wait... what? HOW IS THIS POSSIBLE?!
return thingx.speed();
}
...
vs
public int howFast(Mover mover) {
return mover.speed();
}
Now, imagine having to go back and change all those howFast functions in the future.
Interface or no, each class will have to implement or inherit the speed() method. An interface lets you use those disparate classes more easily, because they've each promised to behave in a certain way. You'll call speed(), and they'll return an int, so you don't have to write separate methods for every possible class.
When you find you need to handle speed differently because of a breakthrough in relativistic physics, you only need to update the methods that call speed(). When your great-granddaughter writes a class for HyperIntelligentMonkeyFish, she doesn't have to disassemble your ancient binary and make changes so that your code can monitor and control her mutant army. She needs only declare that HyperIntelligentMonkeyFish implements Mover.
Interfaces allow Java, since it is statically typed, to work around multiple inheritance limitations to the degree felt worthwhile by the language designers.
In a dynamic language (like Python, Ruby, etc.) you can just call the speed method on any arbitrary object and discover at runtime if it is there or not.
Java, on the other hand, is statically typed, which means the compiler has to agree that the method will be there ahead of time. The only way to do that on classes that don't share common ancestry, and may only have Object in common, is an interface.
Since objects can implement an arbitrary number of interfaces, this means you get the goodness of multiple inheritance (a single object that can pose as multiple different objects for different methods) without the downside (of conflicting implementations in the two super classes).
With Java 8, the designers of the language concluded that interfaces without any implementation was overly restrictive (they didn't like my solution I guess ;-)), so they allow for a default implementation, thus expanding the multi-inheritance options of interfaces, while still trying to avoid the conflicting implementation problem via a complex set of precedence rules so that there is an unambiguous default implementation to execute.
I am trying to explain the advantage of interface with the following example-
suppose you have another class where you need to use the tiger or AeroPlane as parameter. So by using interface you can call using
someObject.someMethod(ClassWithSpeed)
but if you dont use interface you can use
someObject.someMethod(Tiger)
someObject.someMethod(AeroPlane)
Now what should you do? Your probable answer will be like, "I will use two overloaded method".
This is okay so far, But
Say you need to add more options (say car, cycle, rabbit, tortoise.... 100 others). So what will you do to make the change of your existing code?? you will need to change a lots of things..
The overall example above has only one purpose. That is to say
"we need interface to create a better, reusable and properly object oriented
design"
N.B.
if you are sure the program is too small and you will never need to change them then I think it is okay to implement without interface
Defining an interface allows you to define methods that work not only on Aeroplane and Tiger, but also other classes that share the same interface.
For example, say your interface is IObjectWithSpeed. Then you can define a method like this -- in a single class that operates on IObjectWithSpeed objects.
public double calculateSecondsToTravel( IObjectWithSpeed obj, double distance ) {
return distance / obj.getSpeed();
}
Interfaces allow us to satisfy the open/closed principle - open for extension, but closed for modification. The single implementation of the method above doesn't need to be modified as new classes are defined that implement IObjectWithSpeed.
I want go into much theoretical details but will try to explain using this example.
Consider JDBC API. It is API used to deal with database related options in the Java. Now, there are so many databases in the industry. How would one write drivers for that? Well, the quick and dirty approach may be write own implementation using our own classes and API.
But think from the programmer's perspective. Will they start learning DATABASE DRIVER's API while using different database? The answer is NO.
So what is the solution to the problem ? Just have a well defined API which anyone can extend for his own implementation.
In JDBC API, there are some Interfaces which are Connection, ResultSet, PreparedStatement, Statement etc. Now each database vendor will implement the interface and will write his own implementation for that. Result ? : Reduced effort from the developer and easy understandability.
Now, what this custom implementation might consisting of ? It's simple. They do what, take ResultSet interface for example and implement it and in whatever method the ResultSet is gettting returned, return THE CLASS THAT IMPLEMENTS ResultSet interface like this
ResultSet rs=new ResultSetImpl(); //this is what they are doing internally.
So interface are like contracts. They define what your class is able to do and they give your application flexibility. You can create your own APIs using interfaces properly.
Hope this helps you.
An interface is not simply a method signature.
It is a type that represents a contract. The contract is the thing, not the method signatures. When a class implements an interface, it is because there is a contract for a shared behavior that the class has an interest in implementing as a type. That contract is implemented via the specified members which are usually method bodies but may also include static final fields.
It may be true that a tiger and an aeroplane both could be expressed as a type with a common behavior implemented through speed() ... and if so, then the interface represents the contract for expressing that behavior.
Aside from being descriptive for those classes' functionality, methods of an interface could be used without any knowledge about the classes implementing it, even for classes that were not yet defined.
So for example, if you'd need a class Transport that computes say efficient routes, it could be given a class that implements ClassWithSpeed as a parameter and use its method speed() for computing what it needs. This way you could use it with our class Aeroplane, but also with any class we define later, say Boat. Java will take care that if you want to use a class as a parameter to Transport it will implement ClassWithSpeed, and that any class implementing ClassWithSpeed implements the method speed() so that it can be used.
The interface (as a language construct) is used by the compiler to prove that the method call is valid and allows you to have dependent classes interact with the implementing class while having the least possible knowledge about the implementing class.
This is a very wide question to give a simple answer. I can recommend a book Interface Oriented Design: With Patterns. It explains all power of interfaces. And why we should not avoid them.
Have you tried using composition instead?, if I want 2 dissimilar classes to inherit the same abilities I use a class which takes an object of the type its working with by using abstract classes and checking the instances. Interfaces are useful for forcing methods to be including in the class but don't require any implementation or for 2 teams of coders to work on different coding areas.
Class Tiger {
public MovingEntity mover;
public Tiger(){
mover.speed=30;
mover.directionX=-1;
mover.move(mover);
}
}
Class Plane {
public MovingEntity mover;
public Plane(){
mover.speed=500;
mover.directionX=-1;
mover.move(mover);
}
Abstract Class Moverable(){
private int xPos;
private int yPos;
private int directionX;
private int directionY;
private int speed;
Class MovingEntity extends Moverable {
public void move(Moverable m){
if(m instanceof Tiger){
xPos+=directionX*speed;
yPos+=directionY*speed;
}else if(m instanceof Plane){
xPos+=directionX*speed;
yPos+=directionY*speed;
}
}
On language level, the only use of interfaces is, like you mentioned, to be able to refer to different classes in a common way. On people level, however, the picture looks different: IMO Java is strong when used in big projects where the design and the implementation are done by separate people, often from separate companies. Now, instead of writing a specification on a Word document, the system architects can create a bunch of classes that implementers can then directly insert in their IDEs and start working on them.
In other words it is more convenient instead of declaring that "Class X implements methods Y and Z in order for it to be used for purpose A, just to say that "Class X implements interface A"
Because creating interface gives you Polymorphism, across all those classes i.e. Tiger and Aeroplane.
You can extend from an (abstract or concrete) class when the base class's functionality is going to be the core of your child class's functionality as well.
You use interfaces when you want to add an augmented functionality to your class in addition to its core functionality. So using interfaces would give you Polymorphism even when its not your class's core functionality (because you've entered a contract by implementing the interface). This is a huge advantage over creating a speed() method with each class.

"Program to an interface". What does it mean? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
I keep coming across this term:
Program to an interface.
What exactly does it mean? A real life design scenario would be highly appreciated.
To put it simply, instead of writing your classes in a way that says
I depend on this specific class to do my work
you write it in a way that says
I depend on any class that does this stuff to do my work.
The first example represents a class that depends on a specific concrete implementation to do its work. Inherently, that's not very flexible.
The second example represents a class written to an interface. It doesn't care what concrete object you use, it just cares that it implements certain behavior. This makes the class much more flexible, as it can be provided with any number of concrete implementations to do its work.
As an example, a particular class may need to perform some logging. If you write the class to depend on a TextFileLogger, the class is forever forced to write out its log records to a text file. If you want to change the behavior of the logging, you must change the class itself. The class is tightly coupled with its logger.
If, however, you write the class to depend on an ILogger interface, and then provide the class with a TextFileLogger, you will have accomplished the same thing, but with the added benefit of being much more flexible. You are able to provide any other type of ILogger at will, without changing the class itself. The class and its logger are now loosely coupled, and your class is much more flexible.
An interface is a collection of related methods, that only contains the signatures of those methods - not the actual implementation.
If a class implements an interface (class Car implements IDrivable) it has to provide code for all signatures defined in the interface.
Basic example:
You have to classes Car and Bike. Both implement the interface IDrivable:
interface IDrivable
{
void accelerate();
void brake();
}
class Car implements IDrivable
{
void accelerate()
{ System.out.println("Vroom"); }
void brake()
{ System.out.println("Queeeeek");}
}
class Bike implements IDrivable
{
void accelerate()
{ System.out.println("Rattle, Rattle, ..."); }
void brake()
{ System.out.println("..."); }
}
Now let's assume you have a collection of objects, that are all "drivable" (their classes all implement IDrivable):
List<IDrivable> vehicleList = new ArrayList<IDrivable>();
list.add(new Car());
list.add(new Car());
list.add(new Bike());
list.add(new Car());
list.add(new Bike());
list.add(new Bike());
If you now want to loop over that collection, you can rely on the fact, that every object in that collection implements accelerate():
for(IDrivable vehicle: vehicleList)
{
vehicle.accelerate(); //this could be a bike or a car, or anything that implements IDrivable
}
By calling that interface method you are not programming to an implementation but to an interface - a contract that ensures that the call target implements a certain functionality.
The same behavior could be achieved using inheritance, but deriving from a common base class results in tight coupling which can be avoided using interfaces.
Polymorphism depends on programming to an interface, not an implementation.
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to this principle of programming to an interface.
See the Factory Method pattern for further reasoning of this design.
Source: "Design Patterns: Elements of Reusable Object-Oriented Software" by G.O.F.
Also See: Factory Pattern. When to use factory methods?
Real-world examples are applenty. One of them:
For JDBC, you are using the interface java.sql.Connection. However, each JDBC driver provides its own implementation of Connection. You don't have to know anything about the particular implementation, because it conforms to the Connection interface.
Another one is from the java collections framework. There is a java.util.Collection interface, which defines size, add and remove methods (among many others). So you can use all types of collections interchangeably. Let's say you have the following:
public float calculateCoefficient(Collection collection) {
return collection.size() * something / somethingElse;
}
And two other methods that invoke this one. One of the other methods uses a LinkedList because it's more efficient for it's purposes, and the other uses a TreeSet.
Because both LinkedList and TreeSet implement the Collection interface, you can use only one method to perform the coefficient calculation. No need to duplicate your code.
And here comes the "program to an interface" - you don't care how exactly is the size() method implemented, you know that it should return the size of the collection - i.e. you have programmed to the Collection interface, rather than to LinkedList and TreeSet in particular.
But my advice is to find a reading - perhaps a book ("Thinking in Java" for example) - where the concept is explained in details.
Every object has an exposed interface. A collection has Add, Remove, At, etc. A socket may have Send, Receive, Close and so on.
Every object you can actually get a reference to has a concrete implementation of these interfaces.
Both of these things are obvious, however what is somewhat less obvious...
Your code shouldn't rely on the implementation details of an object, just its published interface.
If you take it to an extreme, you'd only code against Collection<T> and so on (rather than ArrayList<T>). More practically, just make sure you could swap in something conceptually identical without breaking your code.
To hammer out the Collection<T> example: you have a collection of something, you're actually using ArrayList<T> because why not. You should make sure you're code isn't going to break if, say, you end up using LinkedList<T> in the future.
"Programming to an interface" happens when you use libraries, other code you depend upon in your own code. Then, the way that other code represents itself to you, the method names, its parameters, return values etc make up the interface you have to program to. So it's about how you use third-party code.
It also means, you don't have to care about the internals of the code you depend on, as long as the interface stays the same, your code is safe (well, more or less...)
Technically there are finer details, like language concepts called "interfaces" in Java for example.
If you want to find out more, you could ask what "Implementing an Interface" means...
I think this is one of Erich Gamma's mantras. I can't find the first time he described it (before the GOF book), but you can see it discussed in an interview at: http://www.artima.com/lejava/articles/designprinciples.html
It basically means that the only part of the library which you're going to use you should rely upon is it's API (Application programming interface) and that you shouldn't base your application on the concrete implementation of the library.
eg. Supposed you have a library that gives you a stack. The class gives you a couple of methods. Let's say push, pop, isempty and top. You should write your application relying only on these. One way to violate this would be to peek inside and find out that the stack is implemented using an array of some kind so that if you pop from an empty stack, you'd get some kind of Index exception and to then catch this rather than to rely on the isempty method which the class provides. The former approach would fail if the library provider switched from using an array to using some kind of list while the latter would still work assuming that the provider kept his API still working.

Categories