Tag Archives: java step pit series

Abstract method and static method of java interface

introduction

before JDK1.8, interface did not provide any concrete implementation. It was described in JAVA programming ideas as follows: “interface is a keyword that produces a completely abstract class. It does not provide any concrete implementation at all. It allows the author to determine the method name, argument list, and return type, but does not have any method body. The interface provides the form, not any concrete implementation.

but this limitation is broken in JDK1.8, where interfaces allow you to define default methods and static methods.

code example

defines an IHello interface

public interface IHello {
	//抽象方法
	void sayHi();
	//静态方法
	static void sayHello() {
		System.out.println("static method : say Hello!");
	}
	//默认方法
	default void sayByebye() {
		System.out.println("default method : say bye!");
	}

}

defines an IHello interface implementation class

public class HelloImpl implements IHello {
	//实现抽象方法
	@Override
	public void sayHi() {
		
		System.out.println("normal method:say hi");
		
	}
}

The

method call

public class App 
{
	public static void main(String[] args)
    {
    	HelloImpl helloImpl = new HelloImpl();
    	//对于abstract抽象方法通过实例对象来调用
    	helloImpl.sayHi();
    	//default 方法只能通过实例对象来调用
    	helloImpl.sayByebye();
    	//静态方法通过 接口名.方法名()来调用
    	IHello.sayHello();
    	
    	//接口是不允许new的,如果使用new后面必须跟上一对花括号用于实现抽象方法,这种方式被称为匿名实现类,匿名实现类是一种没有名称的实现类
    	//匿名实现类的好处:不用再单独声明一个类 缺点:由于没有名称。不能重复使用,只能使用一次
    	new IHello() {			
			@Override
			public void sayHi() {
				System.out.println("normal method;say hi 新定义");			
			}
		}.sayHi();
    }
}

normal method: say hi
default method: say bye!> static method: say Hello!
normal method: say hi new definition