Why are interfaces used in Java when each method needs to be reintroduced into the actual implementation?

Why are interfaces used in Java when each method needs to be reintroduced into the actual implementation? What is an example of a situation where writing an interface makes it easier?

+4
source share
3 answers

Interfaces define a contract, not an implementation. This allows you to divorce the actual implementation of the interface - as long as the implementation satisfies the contract, you are happy.

Let's say you call a method that returns a list (which is an interface). You can use this list because you know that it has List functions such as get () and add (). You do not need to worry about what this list is. If the List is an ArrayList and then the method modifies to return a LinkedList instead, you do not need to change your code at all, since both are guaranteed to have List functions.

+9
source

One of the biggest advantages of interfaces is that you can use the interface in method arguments and return type. For example, you can write:

public List join (List list1, List list2)
{
    // some complicated stuff using list1.size() and list2.get() etc
}
0
source

.

:

public class MyClass {
    public List<String> getNames () {
        List<String> names = new ArrayList<String> ();

        // Populate list of names

        return names;
    }
}

, , , . getNames , List. List; , List, . a ArrayList.

, , LinkedList , List<String> names = new ArrayList<String> (); List<String> names = new LinkedList<String> ();, , . , / .

, ( ) , . Map , .

. , , . , , , /.

API, , API API. DOM XML-, Java. API, , . API // , .

, API. , , Element BuggedElement, . , , , , , BuggedElement.

, API, , , , .

0

All Articles