简体   繁体   English

Java - 实现接口

[英]Java - Implementing Interfaces

I am working on a homework assignment for my into to programming class that involves implementing interfaces. 我正在为我的编程类做一个家庭作业,涉及实现接口。 The problem here is that I really just flat out don't understand interfaces or what they are used for (the professor was not very good about explaining it). 这里的问题是我真的只是不了解接口或它们用于什么(教授对解释它不是很好)。

The assignment was to make a "Vehicle" superclass, and than three subclasses, something like "Truck" or "Jeep" that would each have a couple traits of their own. 分配是制作一个“车辆”超类,而不是三个子类,比如“卡车”或“吉普”,每个都有自己的几个特征。 The "Vehicle" class must implement the comparable interface, which I think I have figured out (I have the compareTo() method written comparing the number of doors on vehicles), and one other class must also implement the "Hybrid" class (I have no idea what this means). “Vehicle”类必须实现类似的界面,我认为我已经想到了(我用compareTo()方法编写比较车辆门的数量),另一个类也必须实现“Hybrid”类(I不知道这意味着什么)。 We then have to implement the toString() , equals(Object o) , and compareTo(Object o) methods. 然后,我们必须实现toString()equals(Object o)compareTo(Object o)方法。

I think I have the compareTo() down, but with the equals() I have no idea. 我想我有compareTo() ,但是使用equals()我不知道。 The last thing we have to do is write a Main to test, this involves making an array of Vehicle objects, printing them out, sorting them, and then re printing them. 我们要做的最后一件事是编写一个Main来测试,这涉及制作一个Vehicle对象数组,打印出来,对它们进行排序,然后重新打印它们。 It should also iterate through the array and print out the price premium for hybrids, and use the equals(Object o) method to compare 2 Vehicles. 它还应该遍历数组并打印混合动力车的价格溢价,并使用equals(Object o)方法来比较2辆车。

Here is the code for my "Vehicle" superclass 这是我的“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;
    }
}

And I will also post one of my subclasses 我还将发布我的一个子类

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

I am definitely not asking anyone to do the work for me, but if someone could shed a bit more light on how interfaces work and what this homework is really asking that would be great. 我绝对不会要求任何人为我做这项工作,但是如果有人能够更多地了解接口如何工作以及这项功课真正要求的那么好。

All help is very much appreciated 非常感谢所有帮助

Thanks! 谢谢!

Rather than doing your particular example I will run through why interfaces are useful and how to use them in a more general case. 而不是做你的特定例子,我将讨论为什么接口有用以及如何在更一般的情况下使用它们。

What is an Interface? 什么是界面?

When I first started programming I also found the concept of an interface to be confusing so I like to think of it as a standard "rule book". 当我第一次开始编程时,我也发现界面的概念令人困惑,因此我喜欢将其视为标准的“规则手册”。 Every class which implements this rule book has a list of "rules" it must follow. 实现此规则手册的每个类都有一个必须遵循的“规则”列表。 For example, consider the following interface: 例如,请考虑以下界面:

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

This above rule book declares an interface for something that bounces. 上面的规则书声明了一个反弹的界面。 It states that anything that is bounceable must set its bounce and also get its bounce. 它指出任何可以反弹的东西都必须设置它的反弹并且也会反弹。 Any class which implements this interface must follow the rule book. 任何实现此接口的类都必须遵循规则手册。

Why would this rule book be useful? 为什么这本规则书会有用?

Well, what if you want to code up a playground, where kids play with all sorts of bouncy things. 那么,如果你想编写一个游乐场,孩子们玩各种有弹性的东西,那该怎么办? You might make the following types of bouncy things.. 您可以制作以下类型的弹性物品..

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

}

The above classes define a type of bouncy ball. 上述类定义了一种弹力球。 You would then make your playground class and could define methods around the abstract Bounceable interface. 然后,您将创建您的playground类,并可以围绕抽象Bounceable接口定义方法。 For example, what if a basketball hoop was a method in your class? 例如,如果篮球圈是你班上的一种方法怎么办? what if it could accept any bouncy thing as an argument? 如果它可以接受任何有弹性的东西作为一个论点怎么办? This would mean that you could pass any kind of ball as long as it implements bounceable. 这意味着只要它实现了可弹性就可以传递任何类型的球。 If you didn't have interfaces or similar functionality you could see how messy your code would get the more balls you implement. 如果你没有接口或类似的功能,你可以看到你的代码有多乱,你实现的球越多。

EDIT: I've included a small practical example.. 编辑:我已经包含了一个小实用的例子..

A practical example of this would be.. 一个实际的例子就是......

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

Both of the following calls to slamDunk are valid... 以下两个对slamDunk的调用都是有效的......

slamDunk(new BaseBall());

slamDunk(new FootBall());

Now your slameDunk function can score points with any bounceable object. 现在你的slameDunk函数可以用任何可跳转的对象得分。

The Comparable interface is described in the docs http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html and has the signature: 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. 

if you write: 如果你写:

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

and then try to compile it, you'll get an error. 然后尝试编译它,你会得到一个错误。 The interface requires that you have to have a method compareTo() . 界面要求您必须有方法compareTo() You have to write it, and it has to return an integer value. 你必须写它,它必须返回一个整数值。 This will be positive, negative or zero according to whether the Vehicle is "greater than", "less than" or equal to another Vehicle. 根据车辆是否“大于”,“小于”或等于另一车辆,这将是正的,负的或零。 YOU decide what "greater than" means - it could be mass, age, value or anything. 你决定“大于”意味着什么 - 它可能是质量,年龄,价值或任何东西。 That's the value of interfaces - it says what you have to do, but not how you have to do it. 这就是界面的价值 - 它说明了你必须做的事情,但不是你必须要做的事情。

Since you want to do this yourself, I suggest you follow any tutorial on Comparable. 既然你想自己做,我建议你按照任何有关Comparable的教程。

As others said, an interface is like a contract for a class. 正如其他人所说,界面就像一个类的合同。 When a class implements an interface it's claiming to behave in a certain way (for example when your class implements Comparable , it's claiming to be comparable to other objects, and it satisfies this contract by implementing the compareTo method.) 当一个类实现一个接口时,它声称以某种方式运行(例如,当你的类实现Comparable ,它声称与其他对象相当,并且它通过实现compareTo方法来满足这个契约。)

It sounds like your trouble isn't with interfaces -- you already implemented Comparable . 听起来你的麻烦不在于接口 - 你已经实现了Comparable You should check for null in your compareTo though. 您应该在compareTo检查null

You ask about about equals(Object o) . 你问关于equals(Object o) That's even easier than compareTo(Object o) -- it needs to return true when the object you're comparing to is the same as this one, and false when it isn't. 这比compareTo(Object o)更容易 - 当你要比较的对象与这个对象相同时它需要返回true ,而当它没有时它需要返回false (Be careful and remember to check against null -- if o is null you should return false). (小心并记住检查null - 如果onull ,则应返回false)。

Also, you ask about toString() , but you already implemented toString() in your code. 另外,你询问toString() ,但是你已经在代码中实现了toString() The only comment is that a particular subclass' toString() should probably mention something special about it (eg that it's a convertible or a hybrid etc...) 唯一的评论是特定的子类' toString()应该提到一些特殊的东西(例如它是敞篷车或混合动力车......)

(In below scenario think of every noun as a class (some time property) in program and every verb as method of a class ) (在下面的场景中,将每个名词视为程序中的一个类(一些时间属性),并将每个动词视为一个类的方法)

You are building a Robot. 你正在建造一个机器人。 You did below things on Robot 1. 2 Eye sensors , 2 hands , 2 legs and a Head (height of robot = 2m) 2. TO communicate to this robot you took out 10 wires out of head, 10 wires out of leg and 13 wires from hand. 你在机器人1上做了以下事情.2个眼睛传感器,2只手,2条腿和一个头部(机器人的高度= 2米)2。为了与这个机器人进行通信,你从头部取出了10根电线,从腿部取出了10根电线,13根手上的电线。

And the logic is if head wire number 1 joins leg wire number 2 then robot will walk. 并且逻辑是如果头线号1连接腿线2号那么机器人将走路。 If wire number 9 in hand joins head wire number 4 and wire 1 of head joins wire 6 of hands then both hands will go up....etc. 如果手中的9号线连接4号线头,1号线连接线6,则双手将上升......等等。 IMP Note - wire 3 on head should never touch wire 5 on leg. IMP注意 - 头上的电线3不应接触腿上的电线5。 Every thing will blow otherwise. 否则每件事都会打击。

What a INTERFACE huh! 什么是INTERFACE啊!

And now imagine this has to be given to somebody seeing Robots first time. 现在想象一下,有人会第一次看到机器人。 Now think of how this robot will be used. 现在想想如何使用这个机器人。


On similar notes when you create a class you should take care of how it will be used by other program. 在创建类的类似注释中,您应该注意其他程序将如何使用它。 Do you want to have public fields (int and string) available to other programs or you want simple functions which will be taking care of all those complex integer logic. 你想让公共字段(int和string)可用于其他程序,或者你想要简单的函数来处理所有那些复杂的整数逻辑。

Interface provides easy way to communicate between 2 classes and while doing that they don't have to worry about what will happen to other things of my class. 界面提供了在两个类之间进行通信的简便方法,在这样做时,他们不必担心我班级的其他事情会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM