I have seen that if I have interface named interfaceABC.
Example:
public class ABController extends AbstractCOntroller {
private interfaceABC inter;
I am confused that why we make object from interface not from class that implemented it.
private interfaceABC inter;
i am confused that why we make object from interface not from class that implemented it
We haven't created an object/instance yet. We simply declared a variable to hold it. We don't make objects from interfaces (you have to use a concrete class to do that), but we will often use interface types instead of the actual concrete class for variable declarations, method parameter types, and method return types.
Take this for exmaple:
List<Example> examples = new ArrayList<Example>();
...
public List<Example> getExamples() { return examples; }
Using the interface List here instead of the concrete class ArrayList follows a common best practice: to use interfaces instead of concrete classes whenever possible, e.g. in variable declarations, parameters types, and method return types. The reason this is considered a best practice is:
Using the interface for declarations and for return types hides an implementation detail, making it easier to modify in the future. For example, we may find that the code works better using a LinkedList rather than ArrayList. We can easily make this change in one place now, just where the list is instantiated. This practice is especially key for method parameter types and method return types, so that external users of the class won't see this implementation detail of your class and are free to change it without affecting their code.
By using the interface, it may be clearer to a future maintainer that this class needs some kind of List, but it does not specifically need an ArrayList. If this class relied on some ArrayList-specific property, i.e. it needs to use an ArrayList method, than using ArrayList<Example> examples = ... instead of List<Example> examples = ... may be a hint that this code relies on something specific to an ArrayList.
It may simplify testing/mocking to use the more abstract List than to use the concrete class ArrayList.
We haven't made an object, we've made a reference.
By using a reference to the interface rather than a concrete class, we are free to swap in a different implementation of the interface, with no changes to this code. This improves encapsulation, and also facilitates e.g. testing (because we can use mock objects). See also dependency injection.
This is actually very useful. Take the example that we're using a list.
public class A {
private List<String> list;
public A(List<String> list) {
this.list = list;
}
}
This allows class A to work with all operations defined by the list interface. The class constructing A can now give any implementation without changing the code of class A, hence promoting encapsulation, code reuse, testing etc. For instance:
new A(new ArrayList<String>());
For a private field, it does not really matter too much, as that's an implementation detail anyway. Many people will still on principle use the interface everywhere they can.
On the other hand, protected fields (and of course the parameters of public methods) form an API that becomes much more flexible by using interfaces, because that allows subclasses/clients to choose which implementation class they want to use, even classes they supply themselves and which didn't even exist when the API was created.
Of course, if you have a public set method or constructor that sets the private field, then you have to use the interface type for the field as well.
Imagine a gift-wrapping stall in a shop that has a machine which will wrap any box.
The machine is simply designed and built to wrap a rectangular box, it shouldn't matter whether there's chocolate in the box or a toy car. If it mattered, the machine would quite obviously be flawed.
But even before you get to that stall, you have to buy that gift: so the cashier scans the barcode first. The barcode scanner is another example of the same principle: it will scan anything as long as it has a recognisable barcode on it. A barcode scanner that only scanned newspapers would be useless.
These observations led to the concept of encapsulation in software design, which you can see in action when a class refers to an object by an interface only, and not its concrete class.
Related
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.
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.
May be this is a little novice question. I always heard people saying interface will hide the implementation details.I can't able to understand what does that mean in a specific way.I will tell what i understood till now.Please Tell me if there is any wrong in my understanding.
Let us suppose, We have a List interface declared like this in our code.
List ls= new ArrayList()
By changing above line like
ArrayList ls= new ArrayList();
I can see every implementation details of ArrayList by Ctrl+click on the methods in my IDE.
If you declare ls as a private variable in a class and only giving getter to that variable will return reference of interface. In that way you don't know what Object that reference is pointing out.In that way you can hide implementation details.
I think there is more to it than this.Please give me more clarity on this one.
Edit:- I know how polymorphism works through interface.My doubt is Hiding implementation details means literally hiding or it means the End user doesn't need to bother about implementation details of it.
Actually, there is not really, but...
The good thing about hiding is, that it is possible to switch the List implementation (ArrayList) by, lets say, BetterList without breaking the getter. The internal BetterList could then have some features, wich should not be exposed.
Further, the BetterList could implement more than one interface (List and some "ElevatedList" for example). So you could expose 2 getters for different use cases pointing to the same object, but different interfaces.
For example:
public class MyObject {
static class BetterList extends ArrayList<String>{
void someInternalLogic(){
//
}
}
private BetterList internalList1=new BetterList();
public List<String> getList1(){
internalList1.someInternalLogic();
return internalList1;
}
private List internalList2=new ArrayList<String>();
public List<String> getList2(){
return internalList2;
}
}
The getList1-getter hides the someInternalLogic method from external user behind the List interface, wich may be useful, if execution of that method should be controlled internally. The getList2-getter hides the ArrayList-Type behind the List interface leaving the freedom to change the implementation of the internalList2 to f.e. LinkedList, wich may be prefered later.
The key word here with the concept of "hiding the implementation" is flexibility because the only constant on software development is called CHANGE. If you are chained to a concrete class behavior the evolution of your code is harder. When your are programming to the interface the user really don't care about the implementation details. So about literally "hiding" in your IDE you can see all the implementations to that interface pressig CTRL+T over the interface name (at least on eclipse).
I have a basic question in Java, but it's a general question in OOP. Why do interfaces allow fields to be set? Doesn't that run contrary to what an interface is supposed to do?
The way I made sense of it, an interface is what in English would be an adjective. So, if my class implements the interfaces Runnable and Serializable, I'm ensuring the user that my class will satisfy the conditions to be Runnable and Seriablizable. However, that would mean interfaces are "stateless", but they are allowed to have fields in Java...
Am I missing something?
All fields in interface are public static final, i.e. they are constants.
It is generally recommended to avoid such interfaces, but sometimes you can find an interface that has no methods and is used only to contain list of constant values.
First of all, there's difference between OOP paradigm and OOP implementation in Java, so same words may mean a bit different things.
In OOP the paradigm interface is what you can do with the object (or what object can do for you). Any object can have several interfaces and thus play different roles. For example, someone may work as a programmer and be able to create programs, but at the same time he may be a husband and father and thus be able to pay the bills for his family and take care of children. Here "programmer", "husband" and "father" are interfaces, and a person is an object that implements them. Note, that interfaces do not imply presence of any specific features (fields) for implementing object, just actions that this object should be able to perform.
Java more or less follows this idea, but as any paradigm implementation has its own features. Java allows describing methods, that is actions that the implementing object should be able to perform, but not any implementation details, thus, nothing about object fields or private methods.
But what about constants (public final static fields)? Are they part of implementation or interface. It could be both. E.g. interface "programmer" can have constant WORK_HOURS set to "8". Thus Java allows you to describe constants in interfaces too.
Note, that Java only helps you to make good OOP design, but it doesn't strongly require it. In particular, not all public methods of an object should exist in interface too. For example, getter and setter methods are normally public, but in fact they are the part of implementation, not interface, and thus it's worth not to bring them into interface.
(Please also note, that most things I described here are about mainstream OOP like in Java, but there are also other kinds of OOP such as prototype-based one, in particular implemented in JavaScript).
What if that interface refers to constants? Wouldn't it be natural to declare them in the interface?
interface IdFinder {
Serializable UNSAVED = new Serializable() {};
/** #returns the given entity's persistent identity,
or {#link UNSAVED} if it hasn't been saved yet,
or null if o is a value object that hasn't a
persistent identity of its own.
*/
Serializable getId(Object o);
}
Yes, you can have constant fields in interfaces, but you are right when you say that "it seems contrary to what an interface is supposed to do", as it is not a good practice. Why would you want to have all your classes that implement an interface with the same constants? You could simply have them in the class that uses them, or if you really need to export them somehow, have them in a separate class utiliy like this:
public class Constants {
private Constants() { }
public static final int ZERO = 0;
public static final int SOME_COMPLEX_NUM = 2124132L;
...
}
You also have enums, if you need to represent a set of constant fields with some meaning. I do not see any "use case" where you would actually need constants in an interface. But could be wrong :)
I'm writing (well, completing) an "extension" of Java which will help role programming.
I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer:
MyClass extends String implements ObjectWithRoles { //implements... is added
/*Added by me */
public setRole(...){...}
public ...
/*Ends of stuff added*/
...//myClass stuff
}
It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. Quite rough, isnt'it?
It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)?
I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use.
My idea was to extends java.lang.Object.. but you can't. (right?)
Other ideas?
I'm new here, but I follow this site so thank you for reading and all the answers you give! (I apologize for english, I'm italian)
If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. (I will look for api-classes in . before looking in the real rt.jar.)
You should consider using composition rather than inheritence to solve this problem; that way you can provide the functionality you need without using up your "one-shot" at inheritence.
For example, the JDK provides a class PropertyChangeSupport, which can be used to manage PropertyChangeListeners and the firing of PropertyChangeEvents. In situations where you wish to write a class that fires PropertyChangeEvents you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality.
public class MyClass extends MySuperClass {
private final PropertyChangeSupport support;
public MyClass() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
protected void firePropertyChangeEvent() {
PropertyChangeEvent evt = new ...
support.firePropertyChangeEvent(evt);
}
}
you can extend Object - every class extends it.
you seem to need something like multiple inheritance - there isn't such a thing in Java
if you want to add functionality, use object composition. I.e.,
YourClass extends Whatever implements ObjectWithRoles {
private RoleHandler roleHandler;
public RoleHandler getRoleHandler() {..} // defined by the interface
}
And then all of the methods are placed in the RoleHandler
If you're talking about adding a role to all your objects I would also consider an annotation-based solution. You'd annotate your classes with something like #Role("User"). In another class you can extract that role value and use it.
I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation. I feel that this would be a lot cleaner than extending all your classes automatically.
I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere.
If you are doing what you are doing, then inheritance is probably not the correct idiom. You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes.
Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. So, you should really consider a solution whereby you delegate/decorate objects. For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class.
If you just want to associate some objects with additional attributes, use a Map (e.g. HashMap).
What you really want to do would be monkey patching, i.e. changing the behaviour of existing classes without modifying their code.
Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition.