java如何做接口
接口的定义与实现
在Java中,接口(Interface)是一种抽象类型,用于定义一组方法规范而不提供具体实现。接口通过interface关键字声明,类通过implements关键字实现接口。
// 定义接口
interface Animal {
void eat();
void sleep();
}
// 实现接口
class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog is eating");
}
@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}
接口的默认方法与静态方法
Java 8及以上版本允许接口包含默认方法(default修饰)和静态方法(static修饰)。默认方法提供默认实现,子类可选择重写;静态方法通过接口名直接调用。
interface Calculator {
default int add(int a, int b) {
return a + b;
}
static void printResult(int result) {
System.out.println("Result: " + result);
}
}
class Main {
public static void main(String[] args) {
Calculator.printResult(new Calculator(){}.add(2, 3)); // 输出: Result: 5
}
}
接口的多继承
Java支持类实现多个接口,解决单继承的限制。多个接口用逗号分隔。
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("Duck is flying");
}
@Override
public void swim() {
System.out.println("Duck is swimming");
}
}
接口的常量定义
接口中可以定义常量(默认是public static final),通过接口名直接访问。
interface Constants {
String NAME = "Interface";
int MAX_VALUE = 100;
}
class Main {
public static void main(String[] args) {
System.out.println(Constants.NAME); // 输出: Interface
}
}
函数式接口与Lambda表达式
Java 8引入函数式接口(仅包含一个抽象方法的接口),支持Lambda表达式简化实现。
@FunctionalInterface
interface Greeting {
void sayHello(String name);
}
class Main {
public static void main(String[] args) {
Greeting greeting = name -> System.out.println("Hello, " + name);
greeting.sayHello("Java"); // 输出: Hello, Java
}
}
接口与抽象类的区别
- 接口:支持多继承,无构造方法,方法默认是
public abstract(Java 8后允许默认方法)。 - 抽象类:单继承,可包含构造方法和成员变量,方法可以是抽象或具体实现。
abstract class Bird {
abstract void fly();
void eat() {
System.out.println("Bird is eating");
}
}
interface Flying {
void fly();
}





