I was learning through interfaces when I noticed that you can now define static and default methods in an interface.

public interface interfacesample2 {
public static void method() {
System.out.println("hello world");
} public default void menthod3() {
System.out.println("default print");
}
}

Kindly explain the difference of the two and also if there's an example of when we would use this would be nice. A little confused on Interfaces.


Differences between static and default methods in Java 8:

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:

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
}
}

3) Both class and interface can have static methods with same names, and neither overrides other!

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..");
}
}

最新文章

  1. ArcGIS Engine开发之空间查询
  2. 用xib自定义UITableViewCell
  3. Win7_提高性能
  4. HDU 5874 Friends and Enemies
  5. Sublime一些设置
  6. String对象
  7. property、synthesize、id
  8. poj 1966 Cable TV Network 顶点连通度
  9. 推荐font-size的单位 % em单位
  10. MFC中实现定时执行与提醒功能(自编代码)
  11. JavaScript面向对象深入理解原型
  12. DataBase MongoDB高级知识-易使用
  13. CentOS修改系统时间
  14. Liunx-cd命令
  15. RSA加密解密算法
  16. T-SQL语言基础(2)之SQL Server体系结构
  17. 转载:IIS 之 连接数、并发连接数、最大并发工作线程数、队列长度、最大工作进程数
  18. YII框架实现 RBAC
  19. 【Canal源码分析】重要类图
  20. 20155318 《网络攻防》Exp3 免杀原理与实践

热门文章

  1. wpf 判断项目中的某个窗体是否已经打开或者已经存在
  2. iOS 更改状态栏文字颜色
  3. MVP架构的一个小例子
  4. 【url ---lib___】笔趣阁(抓取斗罗大陆完整)和(三寸天堂)
  5. 修改一张MyISAM表row_format为fixed为InnoDB表报错处理
  6. 程序面试题——C实现
  7. session传值取值
  8. Python Flask学习笔记(1)
  9. 7.caffe:create_lmdb.sh(数据预处理转换成lmdb格式)
  10. kotlin函数加强