Is there more to an interface than having the correct methods

后端 未结 17 1002
小鲜肉
小鲜肉 2020-11-22 13:37

So lets say I have this interface:

public interface IBox
{
   public void setSize(int size);
   public int getSize();
   public int getArea();
  //...and so          


        
17条回答
  •  盖世英雄少女心
    2020-11-22 14:28

    the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?

    I am updating the answer with new features of interface, which have introduced with java 8 version.

    From oracle documentation page on summary of interface :

    An interface declaration can contain

    1. method signatures
    2. default methods
    3. static methods
    4. constant definitions.

    The only methods that have implementations are default and static methods.

    Uses of interface:

    1. To define a contract
    2. To link unrelated classes with has a capabilities (e.g. classes implementing Serializable interface may or may not have any relation between them except implementing that interface
    3. To provide interchangeable implementation e.g. strategy pattern
    4. Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces
    5. Organize helper methods in your libraries with static methods ( you can keep static methods specific to an interface in the same interface rather than in a separate class)

    Some related SE questions with respect to difference between abstract class and interface and use cases with working examples:

    What is the difference between an interface and abstract class?

    How should I have explained the difference between an Interface and an Abstract class?

    Have a look at documentation page to understand new features added in java 8 : default methods and static methods.

提交回复
热议问题