接口
定义
public interface GroupedInterface extends Interface1, Interface2, Interface3 {}
- 可以继承多个父接口
- 可见性
- 包级
- public
- private: 在一个类内部定义
- protected: 在一个类内部定义
成员
成员变量及方法都默认为public
- 方法
- 抽象方法
- 默认方法
default
:需要实现 - 静态方法
static
:需要实现
- 成员变量
- 常量:默认且只能为
public static final
- 常量:默认且只能为
默认方法
default
关键字修饰,且需要方法体的实现。
继承
当某个接口继承拥有默认方法的接口时,对默认方法的处理具有以下规则:
- 子接口不声明该默认方法,则会直接继承该默认方法
- 子接口重新声明该默认方法,则相当于重新声明该方法为抽象的
- 子接口重新定义(实现)该默认方法,子接口的实现会覆盖父接口的实现
继承
成员变量
- The inherited fields can be used directly, just like any other fields.
- You can declare a field in the subclass with the same name as the one in the superclass, thus
hiding it
(not recommended). - You can declare new fields in the subclass that are not in the superclass.
成员方法
- The inherited methods can be used directly as they are.
- You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus
overriding it
. - You can write a new static method in the subclass that has the same signature as the one in the superclass, thus
hiding it
. - You can declare new methods in the subclass that are not in the superclass.
- You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
私有成员
- A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
- A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.