【问题标题】:Java - Implementing InterfacesJava - 实现接口
【发布时间】:2012-04-28 01:56:56
【问题描述】:

我正在为涉及实现接口的编程课程做作业。这里的问题是我真的完全不理解接口或它们的用途(教授不太擅长解释它)。

任务是创建一个“Vehicle”超类,而不是三个子类,比如“Truck”或“Jeep”,它们每个都有自己的几个特征。 “Vehicle”类必须实现可比较的接口,我想我已经弄清楚了(我编写了compareTo() 方法来比较车辆上的门数),另外一个类也必须实现“Hybrid”类(我不知道这是什么意思)。然后我们必须实现toString()equals(Object o)compareTo(Object o) 方法。

我认为我的 compareTo() 已关闭,但对于 equals() 我不知道。我们要做的最后一件事是编写一个 Main 来测试,这包括制作一个 Vehicle 对象的数组,将它们打印出来,对它们进行排序,然后重新打印它们。它还应该遍历数组并打印出混合动力车的溢价,并使用equals(Object o) 方法比较两辆汽车。

这是我的“车辆”超类的代码

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;
    }
}

我绝对不会要求任何人为我做这项工作,但如果有人能更清楚地了解接口是如何工作的,以及这个作业真正要求的是什么,那就太好了。

非常感谢所有帮助

谢谢!

【问题讨论】:

  • 接口基本上是一个类的契约。它说如果你想称自己为Comparable,你需要实现构成Comparable的这些方法。
  • 接口只是一种强制类的外观和行为标准化的方式。当一个接口定义一个方法时,实现该接口的每个类都必须覆盖该方法,这保证了该类将拥有自己的该方法版本。
  • 我希望你的教授不要读这个问题。 :)

标签: java inheritance interface superclass comparable


【解决方案1】:

我将介绍接口为何有用以及如何在更一般的情况下使用它们,而不是做你的特定示例。

什么是接口?

当我第一次开始编程时,我还发现接口的概念令人困惑,因此我喜欢将其视为标准的“规则手册”。实现此规则手册的每个类都有一个必须遵循的“规则”列表。例如,考虑以下接口:

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 接口定义方法。例如,如果篮球框是您班级中的一种方法怎么办?如果它可以接受任何有弹性的东西作为论据呢?这意味着您可以传任何类型的球,只要它实现了可弹跳。如果你没有接口或类似的功能,你会看到你的代码会变得多么混乱,你实现的球越多。

编辑:我已经包含了一个小的实际示例..

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

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

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

slamDunk(new BaseBall());

slamDunk(new FootBall());

现在您的slameDunk 函数可以使用任何可弹跳的物体得分。

【讨论】:

  • 也感谢您的示例,您的深入回答确实帮助我在作业中更进一步
【解决方案2】:

Comparable 接口在the docs 中描述 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 的教程。

【讨论】:

    【解决方案3】:

    正如其他人所说,接口就像一个类的契约。当一个类实现一个接口时,它声称以某种方式运行(例如,当您的类实现Comparable 时,它声称与其他对象具有可比性,并通过实现compareTo 方法来满足此契约。)

    听起来你的麻烦不在于接口——你已经实现了Comparable。不过,您应该在 compareTo 中检查 null

    您询问有关equals(Object o) 的问题。这甚至比compareTo(Object o) 更容易——当您要比较的对象与此对象相同时,它需要返回true,而当它不是时,它需要返回false。 (小心并记得检查null -- 如果onull 你应该返回false)。

    另外,您询问了toString(),但您已经在代码中实现了toString()。唯一的评论是一个特定的子类'toString() 可能应该提到它的一些特别之处(例如,它是敞篷车或混合动力车等......)

    【讨论】:

      【解决方案4】:

      (在下面的场景中,将每个名词视为一个类(某些时间属性) 在程序和每个动词作为类的方法)

      您正在构建一个机器人。你在机器人上做了以下事情 1. 2个眼睛传感器,2只手,2条腿和一个头(机器人高度= 2m) 2. 为了与这个机器人通信,你从头部取出 10 根电线,从腿取出 10 根电线,从手取出 13 根电线。

      逻辑是,如果 1 号头线连接 2 号腿线,那么机器人就会行走。如果手上的 9 号线与 4 号线头相连,而头上的 1 号线与手上的 6 号线相连,那么双手将上升....等等。 IMP 注意 - 头上的 3 号线不得接触腿上的 5 号线。否则一切都会失败。

      什么接口啊!

      现在想象一下,这必须给第一次看到机器人的人。现在想想如何使用这个机器人。


      在创建类时的类似说明中,您应该注意其他程序将如何使用它。您是否希望其他程序可以使用公共字段(int 和 string),或者您想要简单的函数来处理所有这些复杂的整数逻辑。

      界面提供了在 2 个班级之间进行交流的简便方法,并且在这样做的同时,他们不必担心我班级的其他事情会发生什么。

      【讨论】:

        猜你喜欢
        • 2015-11-08
        • 2017-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        • 2012-03-20
        • 2012-11-27
        • 2021-09-01
        相关资源
        最近更新 更多