javaSE_8系列博客——Java语言的特性(五)--接口和继承(3)--实现接口

实现一个接口

要声明一个实现接口的类,在类声明中包含一个implements子句。你的类可以实现多个接口,所以implements关键字后面是一个由类实现的接口的逗号分隔列表。按照惯例,implements子句紧跟着extends子句,如果有的话。

一个简单的接口,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对象的大小。

注意:在“Relatable”接口中定义的isLargerThan方法采用类型为Relatable的对象。在前面的例子中用粗体显示的代码行将另外一个代码转换为一个RectanglePlus实例。类型转换告诉编译器该对象真的是什么。直接在另一个实例(other.getArea())上调用getArea将无法编译,因为编译器不了解other实际上是RectanglePlus的一个实例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值