java 实现接口(翻译自Java Tutorials)

原文出自 http://www.cnblogs.com/ggjucheng/archive/2012/12/04/2802265.html

英文出自 http://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html

声明一个类实现接口,要在类声明中包含一个implements语句。类可以实现多个接口,所以implements关键字尾随一个逗号隔开的由该类实现的接口。按照惯例,如果有父类继承,implements语句尾随extend语句。

 

一个简单的接口,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。对于strings,它可以比较字符的个数,对于书,可以比较页数,对于学生,可以比较体重等等。对于平面的几何对象,面积将是一个不错的选择(见下面的RectanglePlus类的),对于三维几何对象可以使用体积对比。所有这些类可以实现isLargerThan()方法。

 

实现Relatable 接口

这里是一个Rectangle接口的实现:

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类型的对象。转换other为RectanglePlus实例的那行代码。类型转换告诉编译器,对象实际是什么类型。直接调用other实例的other.getArea()方法将会失败,因为编译器不知道other真正是RectanglePlus实例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值