When should one use interfaces?

2019-01-03 05:53发布

I know that an interface does not have a body just a method definition. But when should I use interfaces? If I provide someone a set of interfaces with no body, why would they feel a need to write the function body? Would they be better off writing their own abstract class with abstract methods in it.

Edited:

I guess the use of Interfaces is more when you are a part of a team. Suppose Team A writes a code for something and they wanted to see if a call to a method. with name getRecords(), is done or not. This will help Team B to write the body of the interface provided to them and Team B has to keep the method name similar so that code of Team A runs.

Just a thought. I might be wrong. I think Interfaces have no use for a single developer.

Edited:

Thanks all for the answers. With what you all have replied, I think Interfaces have more use when you are making something like API?

标签: oop interface
19条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-03 05:58

It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set.

Set<String> names = new HashSet<String>();

This way, you have to change only one line if you decide to use a TreeSet instead.

Also, methods that operate on sets should specify parameters of type Set:

public static void print(Set<String> s)

Then the method can be used for all set implementations.

In theory, we should make the same recommendation for linked lists, namely to save LinkedList references in variables of type List. However, in the Java library, the List interface is common to both the ArrayList and the LinkedList class. In particular, it has get and set methods for random access, even though these methods are very inefficient for linked lists.

You can’t write efficient code if you don’t know whether random access is efficient or not. This is plainly a serious design error in the standard library, and I cannot recommend using the List interface for that reason.

(To see just how embarrassing that error is, have a look at the source code for the binarySearch method of the Collections class. That method takes a List parameter, but binary search makes no sense for a linked list. The code then clumsily tries to discover whether the list is a linked list, and then switches to a linear search!)

The Set interface and the Map interface, are well designed, and you should use them.

查看更多
冷血范
3楼-- · 2019-01-03 06:01

Abstract class v/s interface is always a point of discussion among developers. I would add my 5 cents. Use abstract class when you want to extend a comman base and where you want to provide a default implementation to the abstract method.

Use interface when you want to exactly implement all the abstract methods to the class implementaing the interface and no default body to a method can be provided.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-03 06:02

It's a problem of design (I speak about java world).

The interface allow you to define the behaviour and structure of component (class) of your software without give you constraint in run-time.

The abstract class, instead, gives you a behaviour by default for a method: usefull if you're sure that this code might not change in the lyfe-time of application.

Example:

You have a web application of the commercial system that send an email in some situation (sign up of a new user).

You can use the abstract class SenderCommunication with method boolean sendWithSuccefull(...) if you're sure that the behaviour not will change oftern.

You can use the interface InterfaceSenderCommunication with method boolean sendWithSuccefull(...) if you're not sure that the behaviour not will change often.

Of course, the judice of "change often - not often" depends by 2 elements:

  • How much time I must spent for sync the old code with the new specs?
  • How much the customer pays? ;)
查看更多
贼婆χ
5楼-- · 2019-01-03 06:04

Objects that belong to one category can use an Interface.When ever IS-A relationship exists between objects.

E.g. Text,Image,MP3,FLV,MOV belongs FileType category

If our application allows users to upload 4 file types they all belong to one category called FILE TYPE

  1. Text
  2. Image
  3. Audio
  4. Video

Inside code we would have object for each of the above types.

enter image description here

Assume we need to send a file then

With Out Interface       

enter image description here

With Interface 

enter image description here

So we can assume all file types(Text,Audio etc) to be of type FileFormat.So we form a IS-A relationship.

This helps when returning single data type  instead of returning specific type from a function we can send common type that is FileFormat.

enter image description here

查看更多
看我几分像从前
6楼-- · 2019-01-03 06:06

Interfaces and abstract classes serve different purposes. For a start, an abstract class is only good for inheriting from - it cannot be instantiated directly. You can put implementation code in an abstract class, but that code can only be called from the class that extends it, or through the class that extends it.

example:

public abstract class A {
    public void myFunc() {
        //do some work
    }
}

public class B : A {
    private void someOtherFunc() {
        base.myFunc();
    }
}

public class Z {
    public void exampleFunc() {
        //call public base class function exposed through extending class:
        B myB = new B();
        myB.myFunc();

        //explicitly cast B to A:
        ((A) myB).myFunc();

        //'A' cannot be created directly, do implicit cast down to base class:
        A myA = new B();
        myA.myFunc();
    }
}

The purpose of an interface is to provide a contract - this means the class that implements it has to provide implemetation for the properties or functions declared in the interface, and it has to use the exact same function signatures. This provides surety when i write some code that calls a class that implements an interface, and it is irrelevant what the classes are derived from, or even what language they are written in, or where i got them from. Another cool feature is that i can have several different implementations of the same function signature for different interfaces. Check this example, which uses some of the same classes from the previous sample:

public class Z {
    public void exampleFunc() {
        C myC = new C();
        //these two calls both call the same function:
        myC.myFunc();
        ((IExampleInterface1)myC).myFunc();

        D myD = new D();
        //hmmm... try and work out what happens here, which myFunc() gets called?
        //(clue: check the base class)
        myD.myFunc();

        //call different myFunc() in same class with identical signatures:
        ((IExampleInterface1)myD).myFunc();
        ((IExampleInterface2)myD).myFunc();
    }
}

interface IExampleInterface1
{
    void myFunc();
}

interface IExampleInterface2
{
    void myFunc();
}

public class C : IExampleInterface1
{
    public void myFunc()
    {
        //do stuff
    }
}

public class D : A, IExampleInterface1, IExampleInterface2
{
    void IExampleInterface1.myFunc()
    {
        //this is called when D is cast as IExampleInterface1
    }

    void IExampleInterface2.myFunc()
    {
        //this is called when D is cast as IExampleInterface2
    }
}
查看更多
Deceive 欺骗
7楼-- · 2019-01-03 06:07

An interface is better than an abstract class because you can implement multiple interfaces, and you can only inherit from one abstract class.

So you can do:

class MyRow extends AbstractRow implements ISearchable, ISortable
{

}

Also, search StackOverflow for other similar questions like Need of interfaces in c#

查看更多
登录 后发表回答