接口是一系列方法的声明,是一些方法特征的集合,一个 接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具有不同的行为(功能)。
为什么需要接口类是不完全抽象的,相对于对象是抽象的,而类的方法是具体的。类只能抽象属性,不能抽象行为。接口中的方法是完全抽象的,使用类和接口可以实现属性的抽象和行为的抽象。
语法 基本语法接口中的属性默认由static final修饰,并且需要初始化
接口中的抽象方法,只有声明,没有实现
public interface InterfaceTest{
static final String str = "...";
public void function();
}
public class TestClass implements InterfaceTest{
public void function(){
//方法的实现
}
}
默认方法
接口中default修饰的为默认方法,默认方法需要在接口中实现,实现接口的类可以不重写默认方法 ,也可以重写默认方法,重写后调用的是重写之后的方法
public interface InterfaceTest {
default void function1(){
System.out.println("方法1");
}
default void function2(){
System.out.println("方法2");
}
}
public class TestClass implements InterfaceTest {
@Override
public void function1(){
System.out.println("重写的方法1");
}
}
public class test {
public static void main(String[] args) {
TestClass testClass = new TestClass();
testClass.function1();
testClass.function2();
}
}
运行结果
重写的方法1 方法2
当一个类实现了多个接口,而这些接口中有相同的默认方法,那么这个类必须重写默认方法
静态方法接口中static修饰的方法为静态方法,和类中的静态方法一样,不属于对象,通过InterfaceName.function()调用,静态方法不会被其它类实现
public interface InterfaceTest {
public static void staticFunction(){
System.out.println("这是静态方法");
}
}
public class test {
public static void main(String[] args) {
InterfaceTest.staticFunction();
}
}
运行结果
这是静态方法static final static 静态的 唯一
- 属性:不属于对象,由类名调用
- 方法:不属于对象,由类名调用
- 类:只有内部类能被static修饰
- 代码块:在类加载时调用,与创建对象无关
- 属性:常量,后续不能修改
- 方法:不能被重写
- 类:不能被继承,如String
以门为例,门需要配一个锁,通过锁的开关来实现门的开关。但是锁有很多种,一个门可以装不同种类的锁,比如门闩、密码锁等。
首先定义一个锁的接口
public interface Lock {
void open();
void close();
}
然后定义一个门,这个门需要有一个锁
public class Door {
private Lock lock;
public void setLock(Lock lock){
this.lock = lock;
}
public void openDoor(){
lock.open();
}
public void closeDoor(){
lock.close();
}
}
再定义不同类型的锁实现接口,并穿给门
public class FaceLock implements Lock{
@Override
public void open() {
System.out.println("人脸识别成功,开门");
}
@Override
public void close() {
System.out.println("人脸识别成功,关门");
}
}
测试方法
public class test {
public static void main(String[] args) {
Door door = new Door();
FaceLock faceLock = new FaceLock();
//给门安装锁
door.setLock(faceLock);
door.openDoor();
door.closeDoor();
}
}
输出结果
人脸识别成功,开门 人脸识别成功,关门
还可以再定义一个密码锁
public class PasswordLock implements Lock {
@Override
public void open() {
System.out.println("密码正确,开门");
}
@Override
public void close() {
System.out.println("密码正确,关门");
}
}
再次测试
public class test {
public static void main(String[] args) {
Door door = new Door();
FaceLock faceLock = new FaceLock();
//给门安装人脸识别锁
door.setLock(faceLock);
door.openDoor();
door.closeDoor();
PasswordLock passwordLock = new PasswordLock();
//给门安装密码锁
door.setLock(passwordLock);
door.openDoor();
door.closeDoor();
}
}
输出结果
人脸识别成功,开门 人脸识别成功,关门 密码正确,开门 密码正确,关门
使用接口,可以实现门的不同开门方式,也就是实现了门的行为抽象,在软件开发过程中合理使用接口能很好地提高可扩展性。



