手册
目录
前言:
在本教程中,您将学习如何使用Java接口,接口Java中实现abstraction抽象的另一种方法是使用接口。
Java 中实现abstraction抽象的另一种方法是使用接口。
An interface 接口是一个完全"抽象类",用于将相关方法与空实体分组:
// 接口
interface Animal {
public void animalSound(); // 接口方法(没有主体)
public void run(); // 接口方法(没有主体)
}
要访问接口方法,接口必须由另一个具有 implements 关键字(而不是extends)的类"实现"(类似于继承)。
接口方法的主体由"implement"类提供:
// 接口
interface Animal {
public void animalSound(); // 接口方法(没有主体)
public void sleep(); // 接口方法(没有主体)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// 这里提供了 animalSound() 的主体
System.out.println("The pig says: wee wee");
}
public void sleep() {
// sleep() 的主体在此处提供
System.out.println("Zzz");
}
}
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // 创建 Pig 对象
myPig.animalSound();
myPig.sleep();
}
}
点击 "运行实例" 按钮查看在线实例
abstract 抽象的和public公共的public, static 和 final1) 为了实现安全性-隐藏某些细节,只显示对象(接口)的重要细节。
2) Java不支持"多重继承"(一个类只能从一个超类继承)。但是,它可以通过接口实现,因为该类可以实现多个接口。
注释: 要实现多个接口,请用逗号分隔它们(请参见下面的示例)。
要实现多个接口,请用逗号分隔:
interface FirstInterface {
public void myMethod(); // 接口方法
}
interface SecondInterface {
public void myOtherMethod(); // 接口方法
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
点击 "运行实例" 按钮查看在线实例
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77万人学习
共29课时
61.7万人学习
共25课时
39.3万人学习
共43课时
70.9万人学习
共25课时
61.6万人学习
共22课时
23万人学习
共28课时
33.9万人学习
共89课时
125万人学习