【JavaSE】接口 详解
warning:
这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
在Java中,接口是一种引用类型,它是一种特殊的抽象类,用于定义一组方法规范,而不提供这些方法的具体实现。接口中的所有方法都是抽象的,不能有具体的实现。接口可以包含变量,但这些变量默认是public, static, final的,即全局静态常量。
接口的定义语法如下:
public interface InterfaceName {
// 常量定义
public static final dataType VAR_NAME = value;
// 抽象方法定义
returnType methodName(paramList);
}接口的实现语法如下:
public class ClassName implements InterfaceName {
// 实现接口中的所有抽象方法
public returnType methodName(paramList) {
// 方法实现
}
}接口的实现类必须提供接口中所有方法的具体实现。
下面是一个简单的接口和实现类的例子:
public interface Animal {
void makeSound();
}
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class TestInterface {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound(); // 输出: Woof!
}
}在这个例子中,Animal是一个接口,它定义了一个方法makeSound。Dog类实现了Animal接口,并提供了makeSound方法的具体实现。在main方法中,我们创建了Dog类的实例,并调用了makeSound方法,输出了狗的叫声。
评论已关闭