JDK8新特性接口的静态方法和默认方法

JDK8以后(包括8),允许我们在接口中定义static方法和default方法。但在jdk8之前,interface之中可以定义变量和方法,变量必须是public、static、final的,方法必须是public、abstract的。该特性又叫扩展方法

如何调用新增加的修饰方法?

static静态方法,只能通过接口名调用,不可以通过实现类的类名或者实现类的对象调用。

default方法,只能通过接口实现类的对象来调用。

public interface JDK8Interface {

    //1.默认方法
    default void testDefault()
    {
        System.out.println("默认方法");
    }

    //2.静态方法
    static void testStatic()
    {
        System.out.println("静态方法");
    }

}

1.默认方法和静态方法不需要一定在实现类中去重写它们,当然,你也可以根据需要重写他们

    public class JDK8InterfaceImpl implements JDK8Interface {  
        
    }  

2.调用实例:

    public class Main {  
        public static void main(String[] args) {  
            // static方法必须通过接口类调用  
            JDK8Interface.staticMethod();  

            //default方法必须通过实现类的对象调用  
            new JDK8InterfaceImpl().defaultMethod();  
        }  
    }  
发布了127 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ZGL_cyy/article/details/104182409