Java 中的接口如何实现抽象?
抽象是向用户隐藏实现详情的过程,只向用户提供功能。换句话说,用户了解对象的作用,而不是它如何作用。
由于接口中的所有方法都是抽象的,并且用户除了方法签名/原型之外不知道方法是如何编写的。使用接口,可以实现(完全)抽象。
接口中的抽象
Java 中的接口是对方法原型的规范。每当你需要指导程序员或者订立合同来指定一个类型的方法和字段应该如何使用时,都可以定义一个接口。
要创建此类型的对象,需要实现此接口,为接口的所有抽象方法提供主体,并获取实现类的对象。
希望使用接口方法的用户只知道实现此接口及其方法的类,实现信息对用户完全隐藏,从而实现 100% 的抽象。
示例
interface Person{
void dsplay();
}
class Student implements Person{
public void dsplay() {
System.out.println("This is display method of the Student class");
}
}
class Lecturer implements Person{
public void dsplay() {
System.out.println("This is display method of the Lecturer class");
}
}
public class AbstractionExample{
public static void main(String args[]) {
Person person1 = new Student();
person1.dsplay();
Person person2 = new Lecturer();
person2.dsplay();
}
}输出
This is display method of the Student class This is display method of the Lecturer class
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP