Java - 实现接口

5
我正在为我的编程入门课程完成一项作业,该作业涉及实现接口。问题在于,我真的不理解接口或它们的用途(教授没有很好地解释)。作业要求制作一个“车辆”超类,然后是三个子类,例如“卡车”或“吉普车”,每个子类都有自己的一些特点。 “Vehicle”类必须实现可比接口,我想我已经弄清楚了(我已经编写了compareTo()方法来比较车辆上的门数),还有一个类必须实现“混合”类(我不知道这意味着什么)。然后我们必须实现toString()equals(Object o)compareTo(Object o)方法。
我认为我已经弄清楚了compareTo(),但是对于equals()我一无所知。我们最后要做的是编写一个Main来进行测试,这涉及创建一个Vehicle对象数组,打印它们,对它们进行排序,然后重新打印它们。它还应该遍历数组并打印混合动力汽车的价格溢价,并使用equals(Object o)方法比较2个车辆。
以下是我“Vehicle”超类的代码:
package vehicle;

abstract public class Vehicle implements Comparable {
    private String color;
    private int numberOfDoors;

    // Constructor
    /**
     * Creates a vehicle with a color and number of doors
     * @param aColor The color of the vehicle
     * @param aNumberOfDoors The number of doors
     */
    public Vehicle(String aColor, int aNumberOfDoors) {
        this.color = aColor;
        this.numberOfDoors = aNumberOfDoors;
    }

    // Getters
    /**
     * Gets the color of the vehicle
     * @return The color of the vehicle
     */
    public String getColor() {return(this.color);}
    /**
     * Gets the number of doors the vehicle has
     * @return The number of doors the vehicle has
     */
    public int getNumberOfDoors() {return(this.numberOfDoors);}

    // Setters
    /**
     * Sets the color of the vehicle
     * @param colorSet The color of the vehicle
     */
    public void setColor(String colorSet) {this.color = colorSet;}
    /**
     * Sets the number of doors for the vehicle
     * @param numberOfDoorsSet The number of doors to be set to the vehicle
     */
    public void setNumberOfDoors(int numberOfDoorsSet) {this.numberOfDoors = numberOfDoorsSet;}

    @Override
    public int compareTo(Object o) {
        if (o instanceof Vehicle) {
            Vehicle v = (Vehicle)o;
            return this.numberOfDoors - v.getNumberOfDoors();
        }
        else {
            return 0;
        }
    }

    /**
     * Returns a short string describing the vehicle
     * @return a description of the vehicle
     */
    @Override
    public String toString() {
        String answer = "The car's color is "+this.color
                +". The number of doors is"+this.numberOfDoors;
        return answer;
    }
}

我会同时发布我的一个子类
package vehicle;

abstract public class Convertible extends Vehicle {
    private int topSpeed;

    // Constructor
    /**
     * Creates a convertible with a color, number of doors, and top speed
     * @param aColor The color of the convertible
     * @param aNumberOfDoors The number of doors of the convertible
     * @param aTopSpeed The top speed of the convertible
     */
    public Convertible (String aColor, int aNumberOfDoors, int aTopSpeed) {
        super(aColor, aNumberOfDoors);
        this.topSpeed = aTopSpeed;
    }

    // Getters
    /**
     * Gets the top speed of the convertible
     * @return The top speed of the convertible
     */
    public int getTopSpeed() {return(this.topSpeed);}

    // Setters
    /**
     * Sets the top speed of the convertible
     * @param topSpeedSet The top speed to set to the convertible
     */
    public void setTopSpeed(int topSpeedSet) {this.topSpeed = topSpeedSet;}

    /**
     * Returns a short description of the convertible
     * @return a short description of the convertible
     */
    @Override
    public String toString() {
        String answer = "The car's color is "+super.getColor()
                +", the number of doors is "+super.getNumberOfDoors()
                +", and the top speed is "+this.topSpeed+" mph.";
        return answer;
    }
}

我绝对不是要求任何人为我完成工作,但如果有人能更详细地解释接口的工作原理以及这个作业的真正要求,那就太好了。

非常感谢所有的帮助。

谢谢!


1
接口基本上是一个类的合同。它表示,如果你想称自己为“可比较的”,那么你需要实现这些方法来构成一个“可比较”的类。 - Hunter McMillen
1
接口只是一种强制类以标准化的方式查看和行为的方法。当接口定义一个方法时,实现该接口的每个类都必须覆盖该方法,这保证了该类将拥有自己的该方法版本。 - user377628
3
希望您的教授不会看到这个问题。 :) - Dhananjay
4个回答

12

与其执行您的特定示例,不如我来介绍接口的用途以及如何在更一般的情况下使用它们。

什么是接口?

当我初学编程时,接口的概念对我来说也很困惑,所以我喜欢将其视为一个标准的“规则书”。实现这个规则书的每个类都有一系列必须遵守的“规则”。例如,请考虑以下接口:

interface Bounceable{
  public void setBounce(int bounce);
  public int getBounce();
}

这本规则书定义了一个能够弹跳的接口。规定任何可以弹跳的物体必须设定其弹跳值并获取其弹跳值。任何实现此接口的类都必须遵循这本规则书。

为什么这本规则书会有用呢?

好的,假设你想编写一个游乐场,在那里孩子们可以玩各种各样的弹性物品。你可能会创建以下类型的弹性物品...

public class FootBall implements Bounceable{
private int bounce;

public void setBounce(int bounce){
   this.bounce = bounce;
}

public int getBounce(){
  return this.bounce;
}

}

public class BaseBall implements Bounceable{
private int bounce;

public void setBounce(int bounce){
   this.bounce = bounce;
}

public int getBounce(){
  return this.bounce;
}

}
上述类定义了一种弹跳球的类型。然后您可以创建您的游乐场类,并可以围绕抽象的Bounceable接口定义方法。例如,如果篮球架是您类中的一个方法,会怎样?如果它可以接受任何弹性物体作为参数呢?这意味着您可以传递任何一种球,只要它实现了bounceable接口。如果您没有接口或类似功能,您可以看到实现更多球时您的代码会变得多么混乱。

编辑:我包括了一个小的��际例子...

这个的一个实际例子是..

public void slamDunk(Bounceable bouncyThing){
  System.out.println("You scored three points!");
}

以下两个 slamDunk 的调用方式都是有效的...

slamDunk(new BaseBall());

slamDunk(new FootBall());
现在你的slameDunk函数可以与任何可弹跳的对象得分。

谢谢你的示例,你深入的回答真的帮助我在任务中更进一步。 - salxander

0
你正在建造一个机器人。你在机器人身上进行了以下操作: 1. 安装了2个眼睛传感器、2只手臂、2条腿和一个头(机器人高度=2m)。 2. 为了与这个机器人通信,你从头部取出10根电线,从腿部取出10根电线,从手部取出13根电线。
逻辑是:如果头部电线1连接到腿部电线2,则机器人会行走。如果手部电线9连接到头部电线4,头部电线1连接到手部电线6,则两只手会同时抬起...等等。 重要提示-头部的第3根电线不应该接触到腿部的第5根电线。否则一切都会爆炸。
这是一个多么复杂的接口啊!
现在想象一下,这个机器人将被交给那些首次见到机器人的人使用。

在类的创建中,需要考虑其他程序如何使用它。您想要将公共字段(int和string)提供给其他程序使用,还是想要一些简单的函数来处理所有这些复杂的整数逻辑。

接口提供了两个类之间进行通信的简便方式,而且在此过程中,它们不必担心我的类的其他内容会发生什么事情。


0

正如其他人所说,接口就像是类的契约。当一个类实现了一个接口时,它声称以某种方式行为(例如,当你的类实现了Comparable时,它声称可以与其他对象进行比较,并通过实现compareTo方法来满足这个契约)。

听起来你的问题不在于接口——你已经实现了Comparable。但你应该在compareTo中检查null

你问到equals(Object o)。这比compareTo(Object o)还要容易——当你比较的对象与这个对象相同时,它需要返回true,否则返回false。(要小心并记得检查null——如果onull,你应该返回false)。

此外,你问到toString(),但你已经在代码中实现了toString()。唯一的评论是特定子类的toString()可能应该提到一些特殊的东西(例如,它是可转换的或混合的等等...)


0

Comparable接口在文档http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html中有描述,并具有以下签名:

int compareTo(T o)
Compares this object with the specified object for order. 
Returns a negative integer, zero, or a positive integer as this object is less than, 
equal to, or greater than the specified object. 

如果你写:

public class Vehicle implements Comparable {
//...
}

然后尝试编译它,你会得到一个错误。该接口要求您必须拥有一个方法compareTo()。您必须编写它,并且它必须返回一个整数值。这将根据车辆是“大于”,“小于”还是等于另一个车辆而为正、负或零。您可以自行决定什么是“大于” - 可以是质量、年龄、价值或其他任何东西。这就是接口的价值所在 - 它说明了您必须做什么,但不说明您必须如何做。

由于您想自己完成此操作,我建议您遵循任何关于Comparable的教程。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接