Three newly added methods in java interface: default method, static method, private method

Get into the habit of writing together! This is the 17th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

Default methods in interfaces (new in java 8)


  • Function :
用于接口升级,如果想在已经在定义的接口中添加新的抽象类,如果没有此方法的话那么该接口的所有实现类都要实现该方法,会非常的繁琐
复制代码
  • Definition form :
 public default 返回值类型 方法名(参数列表){} 
 // public可以省略,但是default不可以省略
复制代码
  • example:
 // public default void show() {}
 public interface Inter {
	void show();
	default void method(){
		System.out.println("默认方法执行了...")
	}
 }

复制代码

Static methods in interfaces (new in java 8)


  • Function :
 接口中定义的静态方法只能由该接口来使用
复制代码
  • Definition form :
 public static 返回值类型 方法名(参数列表){ }
 // public可以省略,但是static不可以省略
复制代码
  • Example :
 // public static void show() {}
 public interface Inter {
	void show();
	static void method(){
		System.out.println("静态方法执行了...")
	}
 }
 
 public class InterDemo{
	public static void main(String[] args){
		Inter.method(); //静态方法执行了...
	}
 }
复制代码

Private methods in interfaces (new in java 9)


  • Function :
 由于有了默认方法和静态方法,所以当两个默认方法或者静态方法包含一段相同的代码实现时,为了避免重复写该段代码,可以将其抽出来作为接口的私有方法
复制代码
  • Definition form :
 private 返回值类型 方法名(参数列表){}

 private static 返回值类型 方法名(参数列表){}
复制代码
  • Example :
 //private void show(){}
 //private static void method(){}

 public interface Inter {
 
	default void method_default1(){
		show1();
		show2();
		System.out.println("默认方法1执行了...")
	}
	
	default void method_default2(){
		show1();
		show2();
		System.out.println("默认方法2执行了...")
	}
	
	static void method_static1(){
		//show1(); x  有问题,静态方法不能调用非静态的方法
		show2();
		System.out.println("静态方法1执行了...")
	}
	
	static void method_static1(){
		//show1(); x 有问题,静态方法不能调用非静态的方法
		show2();
		System.out.println("静态方法2执行了...")
	}
	
	private void show1(){
		System.out.println("共同要用的方法1执行了...")
	}
	
	private static void show2(){
		System.out.println("共同要用的方法2执行了...")
	}
 }
复制代码

Guess you like

Origin juejin.im/post/7087439980720553992