接口
- 接口(interface)是所提供的一种重要技术,也是一种特殊的类,结构与抽象类相似。
- 接口体中包含常量的声明(没有变量)和抽象方法两部分。
接口中的所有常量访问权限为public,且为static(可以省略public、final、static修饰符),所有抽象方法的访问权为public,且为abstract。
Column 1 | Column 2 |
---|---|
public static final int n = 10; | int n = 10; |
public abstract void f(); | void f(); |
实现接口:
package OwnCode;
public class InterEx1 {
public static void main(String[] args) {
A a = new A();
System.out.println("接口中的 n :"+ MyInter.n);
System.out.print("实现f() :");
a.f();
}
}
interface MyInter{
int n = 10;
void f();
}
class A implements MyInter{
@Override
public void f() {
System.out.println("成功了!");
}
}
非抽象类A实现MyInter接口,A类必须重写MyInter中的f()。
接口回调:
- “接口回调”借用了C语言中指针回调的技术,表示一个变量的地址在某一个时刻放在一个指针变量中,那么指针变量就可以间接操作该变量中存放的数据。
- java中的接口回调:可以把实现某一个接口的类创建的对象的引用赋值给该接口声明的接口变量,那么该接口变量就可以调用被类实现的接口方法。
package OwnCode;
public class InterEx {
public static void main(String[] args) {
stuImf stu = new Student("张三",10001 ,"软件工程");
stu.display();
}
}
interface stuImf{
void display();
}
class Student implements stuImf {
private String stuName;
private long stuID;
private String stuMajor;
public Student(String stuName, long stuID, String stuMajor) {
this.stuName = stuName;
this.stuID = stuID;
this.stuMajor = stuMajor;
}
@Override
public void display() {
System.out.println(stuName+" "+stuID+" "+stuMajor);
}
}