Comparison of interfaces and abstract classes after Java 8
声明:此博文是因为我在百度上找了很多抽象类与接口的区别,发现都没有把Java 8的新特性描述好,所以自己百度总结了一下,如有遗漏,请私信!
Same point
- Can not be instantiated
- Are included as implementation methods
- All subclasses must be implemented as implementation methods
the difference
- The abstract class is defined by abstract, and the interface is defined by interface
- Abstract classes can only be inherited by single, but can be inherited multiple times, interfaces can not only inherit multiple interfaces, but also be implemented multiple times
- Abstract classes can contain any number of methods with method bodies, but interfaces are not allowed before Java 7, and Java 8 allows multiple default methods
- Abstract classes can have constructors, mainly for initialization, but they cannot be adjusted by themselves. They can only be adjusted by subclasses. There is no constructor for interfaces.
- The access modifier for abstract class access can be arbitrary, but the interface is public by default, and the variables in the interface are public static final modification by default
- An abstract class can have a main method, and we can run it; an interface cannot have a main method.
Attached
Abstract class:
public abstract class Employee
{
private String name;
private String address;
private int number;
// 构造器
public Employee(String name,String address,int number){
this.name = name;
this.address= address;
this.number= number;
}
public abstract double computePay();
//其余代码
}
interface:
public interface IDemo {
// 默认方法,可以有多个
default void fun() {
System.out.println("Default method");
}
public static final Integer DEFAULT_VAR = 1;
// 抽象方法
public abstract void doGet();
}