What is the purpose of the default keyword in Java?

后端 未结 8 723
别那么骄傲
别那么骄傲 2020-12-02 08:28

An interface in Java is similar to a class, but the body of an interface can include only abstract methods and final fields

相关标签:
8条回答
  • 2020-12-02 08:58

    The new Java 8 feature (Default Methods) allows an interface to provide an implementation when its labeled with the default keyword.

    For Example:

    interface Test {
        default double getAvg(int avg) {
            return avg;
        }
    }
    class Tester implements Test{
     //compiles just fine
    }
    

    Interface Test uses the default keyword which allows the interface to provide a default implementation of the method without the need for implementing those methods in the classes that uses the interface.

    Backward compatibility: Imagine that your interface is implemented by hundreds of classes, modifying that interface will force all the users to implement the newly added method, even though its not essential for many other classes that implements your interface.

    Facts & Restrictions:

    1-May only be declared within an interface and not within a class or abstract class.

    2-Must provide a body

    3-It is not assumed to be public or abstract as other normal methods used in an interface.

    0 讨论(0)
  • 2020-12-02 08:59

    Default methods enable you to add new functionality to the interfaces of your apps. It can also be used to have a multi inheritance. In addition to default methods, you can define static methods in interfaces. This makes it easier for you to organize helper methods

    0 讨论(0)
提交回复
热议问题