Java - 实现接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10179178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Implementing Interfaces
提问by salxander
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). We then have to implement the toString()
, equals(Object o)
, and compareTo(Object o)
methods.
任务是创建一个“车辆”超类,而不是三个子类,例如“卡车”或“吉普”,每个类都有自己的几个特征。“Vehicle”类必须实现可比较的接口,我想我已经弄清楚了(我compareTo()
写了比较车辆上门数量的方法),另一个类也必须实现“Hybrid”类(我不知道这是什么意思)。然后,我们必须实现toString()
,equals(Object o)
和compareTo(Object o)
方法。
I think I have the compareTo()
down, but with the equals()
I have no idea. 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. 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.
我想我已经compareTo()
失望了,但equals()
我不知道。我们要做的最后一件事是编写一个 Main 来测试,这涉及制作一个 Vehicle 对象的数组,将它们打印出来,对它们进行排序,然后重新打印它们。它还应该遍历数组并打印出混合动力车的价格溢价,并使用该equals(Object o)
方法比较 2 辆汽车。
Here is the code for my "Vehicle" superclass
这是我的“车辆”超类的代码
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!
谢谢!
回答by Aidanc
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. 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 anykind 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.
上述类定义了一种弹力球。然后,您将创建您的 Playground 类,并可以围绕抽象的 Bounceable 接口定义方法。例如,如果篮球架是您班级中的一种方法怎么办?如果它可以接受任何有弹性的东西作为参数会怎样?这意味着你可以传递任何类型的球,只要它实现了可反弹。如果你没有接口或类似的功能,你会发现你的代码越多,你实现的球就越混乱。
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
函数可以用任何可弹跳的对象得分。
回答by peter.murray.rust
The Comparable interface is described in the docshttp://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.htmland 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()
. 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.
然后尝试编译它,你会得到一个错误。接口要求你必须有一个方法compareTo()
。你必须写它,它必须返回一个整数值。根据车辆是“大于”、“小于”还是等于另一辆车,这将是正数、负数或零。您决定“大于”是什么意思——它可以是质量、年龄、价值或任何东西。这就是接口的价值——它说明了你必须做什么,但没有说明你必须如何去做。
Since you want to do this yourself, I suggest you follow any tutorial on Comparable.
既然你想自己做这件事,我建议你遵循 Comparable 上的任何教程。
回答by trutheality
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
. You should check for null
in your compareTo
though.
听起来您的问题不在于接口——您已经实现了Comparable
. 你应该检查null
你的compareTo
虽然。
You ask about about 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. (Be careful and remember to check against null
-- if o
is null
you should return false).
你问关于equals(Object o)
. 这甚至比compareTo(Object o)
-true
当您要比较的对象与该对象相同时返回它需要返回,而false
当它不相同时,它需要返回。(小心并记住检查null
- 如果o
是null
你应该返回false)。
Also, you ask about toString()
, but you already implemented toString()
in your code. The only comment is that a particular subclass' toString()
should probably mention something special about it (e.g. that it's a convertible or a hybrid etc...)
此外,您询问toString()
,但您已经toString()
在您的代码中实现了。唯一的评论是某个特定的子类toString()
可能应该提及它的一些特别之处(例如,它是敞篷车或混合动力车等......)
回答by Dhananjay
(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 条腿和一个头部(机器人的高度 = 2m) 2.为了与这个机器人通信,你从头部取出 10 根电线,从腿上取出 10 根电线和 13手上的电线。
And the logic is if head wire number 1 joins leg wire number 2 then robot will walk. 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. IMP Note - wire 3 on head should never touch wire 5 on leg. Every thing will blow otherwise.
逻辑是如果头线号 1 连接到腿线号 2 则机器人将行走。如果手上的9号线连接4号线头,头部的1号线连接手的6号线,那么双手都会向上......等。IMP 注意 - 头上的电线 3 不应接触腿上的电线 5。否则,每件事都会发生。
What a INTERFACE huh!
什么界面啊!
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.
接口提供了在 2 个类之间进行通信的简单方法,并且这样做时他们不必担心我的类的其他事情会发生什么。