简体   繁体   中英

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). We then have to implement the toString() , equals(Object o) , and compareTo(Object o) methods.

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.

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!

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 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(new BaseBall());

slamDunk(new FootBall());

Now your slameDunk function can score points with any bounceable object.

The Comparable interface is described in the docs http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html and has the signature:

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.

Since you want to do this yourself, I suggest you follow any tutorial on 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.)

It sounds like your trouble isn't with interfaces -- you already implemented Comparable . You should check for null in your compareTo though.

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).

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 (eg that it's a convertible or a hybrid etc...)

(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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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