脚本宝典收集整理的这篇文章主要介绍了Java™ 教程(实现接口),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
实现接口
要声明实现接口的类,请在类声明中包含implements
子句,你的类可以实现多个接口,因此implements
关键字后面跟着由类实现的接口的逗号分隔列表,按照惯例,如果有extends
子句,则implements
子句紧跟其后。
@H_512_13@样例接口,Relatable 考虑一个定义如何比较对象大小的接口。
public interface Relatable { // this (object calling isLargerThan) // and other must be instances of // the same class returns 1, 0, -1 // if this is greater than, // equal to, or less than other public int isLargerThan(Relatable other); }
如果你希望能够比较类似对象的大小,无论它们是什么,实例化它们的类都应该实现Relatable
。
如果有某种方法来比较从类中实例化的对象的相对“大小”,任何类都可以实现Relatable
,对于字符串,它可以是字符数,对于书籍,它可以是页数,对于学生来说,它可能是重量,等等。对于平面几何对象,面积将是一个不错的选择(参见后面的RectanglePlus
类),而体积适用于三维几何对象,所有这些类都可以实现isLargerThan()
方法。
如果你知道某个类实现了Relatable
,那么你就知道可以比较从该类实例化的对象的大小。
实现Relatable接口
这是在创建对象部分中展现的Rectangle
类,为实现Relatable
而重写。
public class RectanglePlus implements Relatable { public int width = 0; public int height = 0; public Point origin; // four constructors public RectanglePlus() { origin = new Point(0, 0); } public RectanglePlus(Point p) { origin = p; } public RectanglePlus(int w, int h) { origin = new Point(0, 0); width = w; height = h; } public RectanglePlus(Point p, int w, int h) { origin = p; width = w; height = h; } // a method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; } // a method for computing // the area of the rectangle public int getArea() { return width * height; } // a method required to implement // the Relatable interface public int isLargerThan(Relatable other) { RectanglePlus otherRect = (RectanglePlus)other; if (this.getArea() < otherRect.getArea()) return -1; else if (this.getArea() > otherRect.getArea()) return 1; else return 0; } }
因为RectanglePlus
实现了Relatable
,所以可以比较任何两个RectanglePlus
对象的大小。
isLargerThan
方法(在Relatable
接口中定义)采用Relatable
类型的对象,示例中other
转换为RectanglePlus
实例,类型转换告诉编译器对象到底是什么,直接在other
实例上调用getArea
(other.getArea()
)将无法编译,因为编译器不理解other
实际上是RectanglePlus
的实例。
上一篇:定义接口
下一篇:将接口用作类型
以上是脚本宝典为你收集整理的Java™ 教程(实现接口)全部内容,希望文章能够帮你解决Java™ 教程(实现接口)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。