> For the complete documentation index, see [llms.txt](https://lin-4.gitbook.io/cs-notebook-java8/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lin-4.gitbook.io/cs-notebook-java8/interface-changes.md).

# Interface Changes

## Java 8 Interface Changes -- static method, default method

<https://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method>

[Java 8](https://www.journaldev.com/2389/java-8-features-with-examples) interface changes include static methods and default methods in interfaces. Prior to Java 8, we could have only method declarations in the interfaces. But from Java 8, we can have **default methods** and **static methods** in the interfaces.

When it comes to maintaining **backward compatibility** with existing code, however, \_static \_and \_default \_methods are a good trade-off.

### 1.default methods:

<https://www.baeldung.com/java-static-default-methods>

```java
public interface Interface{
    void method(String str);
    default void log(String str){
        System.out.println("I logging::"+str);
    }
}
```

The default methods were introduced to **provide backward compatibility** so that existing intefaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as **defender methods** or **virtual extension methods.**

In a typical design based on abstractions, where an interface has one or multiple implementations, if one or more methods are added to the interface, all the implementations will be forced to implement them too. Otherwise, the design will just break down.

Default interface methods are an efficient way to deal with this issue. They**allow us to add new methods to an interface that are automatically available in the implementations**. Thus, there’s no need to modify the implementing classes.

In this way,**backward compatibility is neatly preserved**without having to refactor the implementers.

1. Java interface default methods will help us in extending interfaces without having the fear of breaking implementation classes.
2. Java interface default methods has bridge down the differences between interfaces and abstract classes.
3. Java 8 interface default methods will help us in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
4. Java interface default methods will help us in removing base implementation classes, we can provide default implementation and the implementation classes can chose which one to override.
5. One of the major reason for introducing default methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions.
6. If any class in the hierarchy has a method with same signature, then default methods become irrelevant. A default method cannot override a method from

   `java.lang.Object`

   . The reasoning is very simple, it’s because Object is the base class for all the java classes. So even if we have Object class methods defined as default methods in interfaces, it will be useless because Object class method will always be used. That’s why to avoid confusion, we can’t have default methods that are overriding Object class methods.
7. Java interface default methods are also referred to as Defender Methods or Virtual extension methods.

### 2.Static Method

**Defining a&#x20;*****static*****&#x20;method within an interface is identical to defining one in a class.** Moreover, a \_static \_method can be invoked within other \_static \_and \_default \_methods.

Java interface static method is similar to default method except that we can't override them in the implementation classes. This feature helps us in avoiding undesired results incase of poor implementation in implementation classes.

eg:

```java
public interface MyData{
    default void print(String str){
        if(!isNull(str))
            System.out.println("MyData Print::"+str);    
    }
    static boolean isNull(String str){
        system.out.println("Interface Null Check");
        return str == null? true:"".queals(str)?true:false;
    }
}
```

```java
public class MyDataImpl implements MyData{
    public boolean isNull(String str){
        System.out.println("Impl Null Check");
        return str == null?true:false;
    }
    public static void main(String[] args){
        MyDataImpl obj = new MyDataImpl();
        obj.print("");
        obj.isNull("abc");
    }
}
```

Important points about java interface static method:

1. Java interface static method is part of interface, we can’t use it for implementation class objects.
2. Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.
3. Java interface static method helps us in providing security by not allowing implementation classes to override them.
4. We can’t define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”. This is because it’s not allowed in java, since Object is the base class for all the classes and we can’t have one class level static method and another instance method with same signature.
5. We can use java interface static methods to remove utility classes such as Collections and move all of it’s static methods to the corresponding interface, that would be easy to find and use.

The idea behind*static\_interface methods is to provide a simple mechanism that allows us to**increase the degree of**\[**cohesion**]\(*<https://en.wikipedia.org/wiki/Cohesion>%28computer\_science%29)of a design by putting together related methods in one single place without having to create an object.

Pretty much**the same can be done with abstract classes.**&#x54;he main difference lies in the fact that**abstract classes can have constructors, state, and behavior**.

Furthermore, static methods in interfaces make possible to group related utility methods, without having to create artificial utility classes that are simply placeholders for static methods.

## static VS default methods in interface

1. Default methods can be overriden in implementing class, while static cannot.
2. Static method belongs only to Interface class, so you can only invoke static method on Interface class, not on class implementing this Interface, see:

eg:

```java
public interface MyInterface {
    default void defaultMethod(){
        System.out.println("Default");
    }

    static void staticMethod(){
        System.out.println("Static");
    }    
}

public class MyClass implements MyInterface {

    public static void main(String[] args) {

        MyClass.staticMethod(); //not valid - static method may be invoked on containing interface class only
        MyInterface.staticMethod(); //valid
    }
}
```

1. Both class and interface can have static methods with same names, and neither overrides others!

```java
public class MyClass implements MyInterface {

    public static void main(String[] args) {

        //both are valid and have different behaviour
        MyClass.staticMethod();
        MyInterface.staticMethod();
    }

    static void staticMethod(){
        System.out.println("another static..");
    }
}
```

## Interface

* An interface can contain any number of methods.
* You cannot instantiate an interface.
* An interface does not contain any constructors.
* An interface cannot contain instance fields. the only fields that can appear in an interface must be declared both static and final.
* An interface is not extended by a class; it is implemented by a class.
* An interface can extend multiple interfaces.

Implementation

It is mandatory to **implement all** the methods in a class that implements an **interface** unless and until that class is an Abstract class.

You have **two** choices: -implement every method required by the interface or - **declare** the **missing methods** **abstract** in your class.
