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声明的几点注意事项: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);
}
}一个类如果同时实现多个接口,有可能会有命名冲突,例如两个接口里有相同名字和参数的函数。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);
}
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,那么只需要修改一个地方就可以了。Learn Java for Android Development Second Edition 笔记(六)- Interface,布布扣,bubuko.com
Learn Java for Android Development Second Edition 笔记(六)- Interface
原文地址:http://blog.csdn.net/lyndon2013/article/details/25007517