基本介绍
public interface AInterface {
//写属性
public int n1 = 10;
//写方法
//在接口中,抽象方法,可以省略abstract关键字
public void hi();
//在jdk8后,可以有默认实现方法,需要使用default关键字修饰
default public void ok(){
System.out.println("ok");
}
//jdk8后,可以有静态方法
public static void cry(){
System.out.println("111");
}
}
一些细节
1.接口不能实例化
2.接口中的所有方法是public方法,是抽象方法,但可以不用abstract修饰
3.一个普通类实现接口,就必须将接口的所有方法都实现, 可以用alt + enter快捷键
4.抽象类实现接口时,可以不实现接口的抽象方法
interface IB{
//接口中的属性只能是final的,而且是public static final修饰符
int n1 = 10; //等价 public static final int n1 = 10;
void hi();
}
interface IC{
void hello();
}
//接口不能继承别的类,但可以继承多个别的接口
interface ID extends IB, IC{}
//接口的修饰符只能是public和默认,这点和类的修饰符是一样的
interface IE{}
//一个类可以同时实现多个接口
class Pig implements IB, IC{
@Override
public void hi() {
}
@Override
public void hello() {
}
}
接口VS继承
- 当子类继承了父类,就自动拥有父类的功能
- 如果子类需要扩展功能,可以通过实现接口的方式扩展
- 可以理解 实现接口 是对java单继承机制的补充
接口的多态
public class InterfacePolyParameter {
public static void main(String[] args) {
//接口的多态体现
//接口类型的变量 if01 可以指向 实现了IF接口的对象实例
IF if01 = new Monster();
if01 = new Tiger();
//继承体现的多态
//父类类型的变量a 可以指向继承了AAA的子类的对象实例
AAA a = new BBB();
a = new CCC();
}
}
interface IF{}
class Monster implements IF{}
class Tiger implements IF{}
class AAA{}
class BBB extends AAA{}
class CCC extends AAA{}
多态传递
public class InterfacePolyPass {
public static void main(String[] args) {
IG ig = new Teacher();
//如果IG 继承了 IH 接口,而Teacher类实现了IG接口
//那么,实际上就相当于Teacher也实现了IH接口
//这就是所谓的多态传递现象
IH ih = new Teacher();
}
}
interface IH{
void hi();
}
interface IG extends IH{}
class Teacher implements IG{
@Override
public void hi() {
}
}
例题
interface A_{
int x = 0; //就是public static final int x = 0
}
class B_{
int x = 1;
}
class C extends B_ implements A_{
public void pX(){
// System.out.println(x); //错误,x不明确
//可以明确的指定x
//访问接口的 x 就用 A_.x
//访问父类的 x 就用 super.x
System.out.println(A_.x + " " + super.x);
}
public static void main(String[] args) {
new C().pX();
}