接口
1.接口的概述
-
接口就是一种公共的规范标准,只要符合规范标准,大家都可以通用。
-
Java中的接口更多的体现在对行为的抽象!
2.接口的特点
-
接口用关键字interface修饰
public interface 接口名 {}
-
类实现接口用implements表示
public class 类名 implements 接口名 {}
-
接口不能实例化
-
接口如何实例化呢?参照多态的方式,通过实现类对象实例化,这叫接口多态。
-
多态的形式:具体类多态,抽象类多态,接口多态。
-
-
接口的子类
-
要么重写接口中的所有抽象方法
-
要么子类也是抽象类
-
3.3接口的成员特点
-
成员特点
-
成员变量
- 只能是常量
- 默认修饰符:public static final
-
构造方法
- 没有,因为接口主要是扩展功能的,而没有具体存在
-
成员方法
-
只能是抽象方法
-
认修饰符:public abstract
-
-
-
代码演示
- 接口
public interface Inter { public int num = 10; public final int num2 = 20; // public static final int num3 = 30; int num3 = 30; // public Inter() {} // public void show() {} public abstract void method(); void show(); }
- 实现类
public class InterImpl extends Object implements Inter { public InterImpl() { super(); } @Override public void method() { System.out.println("method"); } @Override public void show() { System.out.println("show"); } }
- 测试类
public class InterfaceDemo { public static void main(String[] args) { Inter i = new InterImpl(); // i.num = 20; System.out.println(i.num); // i.num2 = 40; System.out.println(i.num2); System.out.println(Inter.num); } }