Learn Java for Android Development Second Edition 笔记(六)- Interface
Interface
Declaring Interfaces
interface Drawable { int RED = 1; // For simplicity, integer constants are used. These constants are int GREEN = 2; // not that descriptive, as you will see. int BLUE = 3; int BLACK = 4; void draw(int color); }interface声明的几点注意事项:
- 如果需要被别的package访问,interface前可以加public,否则默认只能被package内部的其他类访问。
- interface前没有必要再加abstract,因为它实际上已经是abstract的了。
- interface里面的成员变量的属性是public final static,没有必要再显示加上这三个属性。
- interface里面的成员变量必须显示初始化。
- interface里面的成员函数属性是public abstract,没有必要再显示加上这两个属性。
- interface里面的成员函数不能声明为static的,因为interface里的成员函数都是instance method。
- 没有成员的interface称为marker interface
Implementing Interfaces
class Point implements Drawable { @Override public void draw(int color) { System.out.println("Point drawn at " + toString() + " in color " + color); } }上面实现接口要注意两个地方,一个是draw函数前要加上public,因为接口定义里上public,另外一个是加上@Override。
public static void main(String[] args) { Drawable[] drawables = new Drawable[] { new Point(10, 20), new Circle(10, 20, 30) }; for (int i = 0; i < drawables.length; i++) drawables[i].draw(Drawable.RED); }以上方法也实现了多态。
public static void main(String[] args) { Drawable[] drawables = new Drawable[] { new Point(10, 20), new Circle(10, 20, 30) }; for (int i = 0; i < drawables.length; i++) drawables[i].draw(Drawable.RED); Fillable[] fillables = new Fillable[drawables.length]; for (int i = 0; i < drawables.length; i++) { fillables[i] = (Fillable) drawables[i]; fillables[i].fill(Fillable.GREEN); } }一个类如果同时实现多个接口,有可能会有命名冲突,例如两个接口里有相同名字和参数的函数。
Extending Interfaces
interface可以继承,例如以下例子:interface Colors { int RED = 1; int GREEN = 2; int BLUE = 3; int BLACK = 4; } interface Drawable extends Colors { void draw(int color); } interface Fillable extends Colors { void fill(int color); }
Why Use Interfaces?
Java里面提供interface接口并不仅是因为没有提供多重继承的功能,而是更为重要地实现一个理念:将接口和实现分离,面向接口编程(接口可以由interface或abstract class实现)。ArrayList<String> arrayList = new ArrayList<String>(); void dump(ArrayList<String> arrayList) { // suitable code to dump out the arrayList }上面例子中将ArrayList类具体到了很多地方,如果某天想要变换使用一种类型的List如LinkedList,那么就需要修改很多地方。以上例子可以改成依赖于接口而不是具体的实现类,例如:
List<String> list = new ArrayList<String>(); void dump(List<String> list) { // suitable code to dump out the list }改成以上方式后,如果要换用LinkedList,那么只需要修改一个地方就可以了。
- 这两个是Java提供的两种抽象类型,不能被直接实例化
- Interface不依赖于任何类,可以有任何类来实现。
- Abstract Class可以和Interface联合起来使用。
Learn Java for Android Development Second Edition 笔记(六)- Interface,,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。