Java - Implementing Interfaces

java interface vs abstract class
java abstract class
implementing multiple interfaces in java
abstraction in java
interface in java javatpoint
multiple inheritance using interface in java
interface in java pdf
interface in java in hindi

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.

Interfaces in Java, The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than  Implementing an Interface. To declare a class that implements an interface, you include an implementsclause in the class declaration. Your class can implement more than one interface, so the implementskeyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implementsclause follows the extendsclause, if there is one.


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.

Interface in java with example programs, An implementation class itself can be abstract and if so, interface methods need not be implemented. When implementation interfaces, there are several rules −. A  Java - Interfaces Declaring Interfaces. The interfacekeyword is used to declare an interface. An interface is implicitly abstract. Implementing Interfaces. When a class implements an interface, you can think of the class as signing a contract, Extending Interfaces. An interface can extend


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

Java - Interfaces, Interface methods do not have a body - the body is provided by the "implement" class; On implementation of an interface, you must override all of its methods  A class that implements an interface must implement all the methods declared in the interface. To implement interface use implements keyword. Why do we use interface ? It is used to achieve total abstraction. Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance . It is also used to achieve loose coupling. Interfaces are used to implement abstraction.


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

Java Interface, A Java class can implement multiple Java Interfaces. All methods in an interface are implicitly public and abstract. Syntax for Declaring Interface An implementation of an interface is a Java program that references the interface using the implements keyword. The program is required to provide method logic for all non-default methods. Optionally, the program can provide an implementation of a default method defined in the interface.


What is Interface in Java with Example, A class that implements an interface must implement all the methods declared in the interface. The  Implementing Java interfaces A class implements an interface by appending Java's implements keyword followed by a comma-separated list of interface names to the class header, and by coding each


Java Interfaces, To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the interfaces implemented by​  1) To achieve security - hide certain details and only show the important details of an object (interface). 2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).


Implementing an Interface, We will learn how to implement interfaces and when to use them in detail with the help of examples. In Java, an interface  of a method in a Java interface, to make the implementation of the interface easier for classes implementing the interface. You can use interfaces in Java as a way to achieve polymorphism. I will get back to polymorphism later in this text.