Java 接口实现关键字: 'implements'
在 Java 中,'implements' 关键字用于实现接口。接口定义了方法的签名,但没有实现它们。类通过实现接口来承诺提供接口中定义的所有方法的实现。
语法:
public class MyClass implements MyInterface {
// 方法实现
}
示例:
interface Drawable {
void draw();
}
class Rectangle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.draw(); // 输出: Drawing a rectangle
}
}
解释:
Drawable接口定义了draw()方法。Rectangle类实现Drawable接口,并提供draw()方法的实现。- 在
Main类中,创建Rectangle对象并调用draw()方法,执行Rectangle类中提供的实现。
使用 'implements' 关键字的好处:
- 多态性: 接口允许创建具有相同行为但不同实现的对象。
- 代码复用: 接口允许代码在多个类中复用。
- 可扩展性: 接口使添加新功能更容易,而无需修改现有代码。
注意:
- 一个类可以实现多个接口。
- 类必须提供所有接口方法的实现。
原文地址: https://www.cveoy.top/t/topic/n0Xa 著作权归作者所有。请勿转载和采集!