接口的默认方法和静态方法接口默认方法在 Java 8 之前,接口允许定义public static final常量和public abstract方法,即使不显式写public static final或public abstract,编译器也会自动添加。同时,不允许定义方法实现(即非抽象方法)。
由于接口中的方法只能是public static final,所以所有实现这个接口的类都必须实现这些方法。这就导致一个严重的问题:
一旦接口发布,就不能轻易。否则所有实现类都必须修改、编译,否则就会编译失败。
这对于大型框架或公共 API 是灾难性的:每次新增方法都可能破坏成百上千个实现类。
default 方法Java 8 引入 default 方法,允许在接口中提供方法的默认实现。
这种方法可以允许方法有自己的默认实现,而不需要子类去覆盖它。已有的实现类不需要修改就能继续工作,如果它们想要自定义行为,也可以选择性地重写默认方法。
1234567interface Animal { void speak(); default void walk() { ...
Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.
Quick StartCreate a new post1$ hexo new "My New Post"
More info: Writing
Run server1$ hexo server
More info: Server
Generate static files1$ hexo generate
More info: Generating
Deploy to remote sites1$ hexo deploy
More info: Deployment
