New features

In the past, there was a big difference between abstract classes and interfaces. For example, you could write function implementations in abstract classes but not in interfaces

That all changed in Java8, with the addition of the default interface and the static keyword

The sample

In the new interface, we can define:

public interface IPerson {

    static String getName(a) {
        return "person";
    }
    
    default Integer getSex(a) {
        return 1;
    }
    
    String getAddress(a);

}

public class Person implements IPerson {
    @Override
    public String getAddress(a) {
        return null; }}Copy the code

GetName and getSex can be called directly at the interface level:

public class Test {

    public void test(a) {
        IPerson.getName();
        newPerson().getSex(); }}Copy the code

Pay attention to

Although interfaces can write methods, they are fundamentally different from abstract classes:

function An abstract class interface
Method implementation Square root √(but cannot override equals/hashCode/toString)
Multiple inheritance x Square root
variable all Only static and final variables can be declared