接口实际上是一种规范。实现接口,是对 Java 单继承的一种补充。接口也具有多态性。

注意事项:

  1. 接口不能被实例化
  2. 接口中的所有方法都是 public 类型,接口中的抽象方法可以不用 abstract 修饰
  3. 一个普通类实现接口就必须将接口中的所有方法实现
  4. 抽象类去实现接口时,可以不实现接口的抽象方法
  5. 一个类可以实现多个接口
  6. 接口中的属性,只能是 final,而且是 public static final 修饰符
  7. 接口中属性的访问形式:接口名.属性名
  8. 接口不能继承其他的类,但是可以继承多个别的接口
  9. 接口的修饰符只能是 public 和默认,和类的修饰符一样

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//camera.java
package com.pushihao.接口;

public class camera implements machine {

@Override
public void work() {
System.out.println("the camera is working");
}

@Override
public void stop() {
System.out.println("the camera is stopping");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//computer.java
package com.pushihao.接口;

public class computer implements machine{
@Override
public void work() {
System.out.println("the computer is working");
}

@Override
public void stop() {
System.out.println("the computer is stopping");
}

public void play() {
System.out.println("the computer can play games");
}
}
1
2
3
4
5
6
7
//machine.java
package com.pushihao.接口;

public interface machine {
void work();
void stop();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//interface.java
package com.pushihao.接口;

public class Interface {
public static void main(String[] args){
machine[] machines = new machine[2];
machines[0] = new camera();
machines[1] = new computer();

for (machine i:machines){
i.work();
i.stop();

//instanceof判断运行类型
if (i instanceof computer){
((computer) i).play();
}
}
}
}