This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 6 years ago.
I can't understand a simple thing.
example: A is an interface, B is a class that implement correctly A.
What dose exactly mean doing:
A name = new B(some_argument);
I see lot of people using this instead of
B name = new B(some_argument);
But I can't figure out what dose that mean making an object with an interface.
And WHY they do this? There are some differences between them?
Sometimes one is better than other?
for example the opposite dose not work
B name = new A();
technically both works.
The reason most people use the first solution (and you should do that too) is that an interface defines a certain contract / API for a type of classes.
That means an interface is used when you dont know the implementation of it or the implementation is exchangeable.
So coding against the interface and not against the real specific implementation is the best way to make your code exchangeable and generic which helps you to modularize your code, keep hard-linked-dependency between classes as low as possible and make your code maintainable.
Also an interface can be used to add additional functionality to a class as you can implement multiple interface but only extend one class.
A practical example:
Think of an SDK for a plugin. It defines some interface.
How do you want to call a function of a class implementing this interface when the implementation of that interface is done by an other guy wrinting a plugin two years after you developed your application/sdk? ;)
Related
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 2 years ago.
I'm trying to wrap my head around interfaces and I've been reading a lot of similar questions/answers on the topic, but it's still not clicking with me. I understand what an interface literally is, but I don't get why you would ever use it.
So an interface contains a bunch of empty functions, and you then implement that interface in a class. But what I don't get is, you still have to write a full function declaration for any function you take from the interface. So say you have a function 'void printHello()' in your interface, and you implement that interface in a class. You still have to write:
public void printHello() {
System.out.println("Hello!");
}
which is a complete function declaration. You could delete the 'implements interface' command and literally nothing would change, you would still have a working function 'printHello()'. So functionally speaking, isn't the interface basically doing nothing? To go further, you could have another class that also implements the same interface, but you could make the same function do something completely different:
public void printHello() {
System.out.println("Bababooey!");
}
So it's not like it's pre-defining functions so you can call them anywhere like a class/object would do. If this is the case what is the interface really providing?
By using interfaces you outsource the responsibility of logic implementation to the classes which implements that interfaces, this is called API.
Lets say you have a List which is an interface and which is implemented by a bunch of different classes like LinkedList or ArrayList. By using List you are flexible to utilize any implementation of that List which varies on your particular needs and simply switch to a different one later on, whereas you code remains the same -- you still use List. So doing an add method you are not interested or you don't care how it is done, you just want to add an element to the collection and how it is implemented internally it is not your business.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why are variables declared with their interface name in Java?
How should lists be cast to their conrecte implementations?
Example:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Thanks.
This is usually so that you can swap in another implementation later and still have the code operate the same. For example, if you then decided to use a TreeMap instead of a HashMap, you could just change the instantiation step, and the rest of your code would still work just fine.
It a programming practice called programming to an interface.
You could switch implementations (e.g. in your example switch to a TreeMap) without affecting the rest of the code, since it will use the base class i.e. Map.
It decouples your code and is considered a good programming practice to code against an interface instead of a concrete implementation
Design by Contract or "Programming to an Interface" are principles that ensure that your code only uses the properties/methods exposed by the interface, and more importantly, one primary interface at any given time. If you're using multiple interfaces at a time, that is generally a sign of tighter coupling.
In general, you should not instantiate objects directly in your code either. You should delegate that job to an external entity so that any changes of the implementation used, can be done in a single place.
There was a Dr Dobb's Journal article that the 'new' keyword should be forbidden (exact title was something like 'new is verboten') but I can't find a link to it right now.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
First of all I think there are difference between the term interface and interface in java and I dont quite get what the difference is.
My first question when it says "Program to an interface rather than to an implementation" is that mean Interface or java Interface?
Im reading headfirst design patterns and I confused about program to an interface rather than program to an
implementation. My understanding is that SUBCLASS IS THE CONCRETE IMPLEMENTATION and the INTERFACE is the
SUPERCLASS(interface or abstract class or simpleclass).
My Second question is when they say program to an interface is that mean that the code is in the INTERFACE(superclass) then subclass just inherited it?? and if they say program to IMPLEMENTATION(subclass) the code is in the subclass??
I think about this because of the the term "ReUse", because if you change your code and your code is in the Subclass(concrete implementation) then you need to change all you subclass codes, then if you put your codes in the interface you just need to change the code in that interface.
also examples(please make it easy) of program to an interface and implementation will help.
3rd question what is the advantages if we program to an interface than if we program to concrete classes?
First of all I must say I have not read that book so I cannot say for sure this is what the author meant, but this is how I understand the sentence.
My understanding of what it means is that you should program in a way where you treat your classes and methods as black boxes, where you don't rely on some internal mechanisms and how they work, but you rather rely on the specifications you or someone else defined in the Interfaces, Superclasses, Documentation, etc. This way you can easily change the implementation without affecting the rest of your code base.
A nice example for this may be storing a sequence of some data, let's say names. You can define functions to add new names, delete them and print them. If you define these functions in an interface like the one below you can use them without having to bother whether the class that implements them uses arrays or lists to store them.
interface Sequence {
void add(String s);
void delete(String s);
void print();
}
Now you can create a class SequenceAsList that implements the interface and use this in your application. Let's say everything works fine, but you now decided that maybe in some places you know the number of item in the sequnce in advance and you need a better performance and hence you would like to use array instead of list. So you can create another class SequnceAsArray that also implements the Sequence interface. Now everything you will need to change in your code will be to do
Sequence someSequence = new SequenceAsArray();
instead of
Sequence someSequence = new SequenceAsList();
Because they followed the same interface it's really easy to do this. Hence I think what the author mainly suggests is to take this approach of taking classes and methods as black boxes.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use abstract class or interface?
I am a newbie in Java , can anyone please explain a scenario where abstract class will be
useful and interface will not be and vice versa.
I believe in not so complex problems both can solve the issue with equal ease.
Please explain in layman's term and pardon my ignorance!
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
This question already has answers here:
Closed 12 years ago.
I have a class which inherits from two different interfaces. Both interfaces declare a method with the same name. How can I provide a different implementation for each interface ?
In C#, the answer is there, but it does not work in java:
Inheritance from multiple interfaces with the same method name
I thought about providing a union implementation which uses type comparison but it's kind of ugly.
Thanks
EDIT : closed, my question was a duplicate of the following, thank you for the answers !
Java - Method name collision in interface implementation
You can't. Interfaces describe behavior, but they don't implement it. So if you implement a method, there's no way to tell which interface you are implementing it from.
No, there's no equivalent feature in Java.
And you can't do it yourself, because inside the method, you have no way of telling if the calling code is referencing the object as InterfaceA or InterfaceB. Even if you could, I think it would be a bad idea.