Search code examples
javaobjectinterfaceabstract-class

Interfaces and Comparable


i'm beginner and just learning abstract classes and interfaces but really struggeling to get it right.

MY Class structure.

  • Abstract Class Vehicle
  • Class Car (extends Vehicle, implements ITuning)
  • Class Motorcycle (extending Vehicle)
  • Interface ITuning

I want to have an abstract method doRace() that I can use in my Car class to compare the Car Objects (car.getHp()) and prints the winner. I try to implement a doRace(object o) into the Interface ITuning and a doRace(Car o) into my Car class but get the error. How can I implement that correctly ?

The type Car must implement the inherited abstract method ITuning.doRace(Object)

But if do chage it to Object, i can't use it in my Car class…

public interface ITuning
{
abstract void doRace(Object o1);
}
public Car extends Vehicle implements ITuning
{
 public void doRace(Car o1){
 if(this.getHp() > o1.getHp())
 };
}

Any Idea what i'm doing wrong? I assume its a comprehension error


Solution

  • You can change your ITuning interface to

    public interface ITuning
    {
        void doRace(Vehicle other);
    }
    

    Since Vehicle defines the getHp() method this ensures that your actual implementation can access it.

    The difference to Chaosfire's answer is that this will allow you to do a race between different types of vehicles, e.g. a Car and a Motorcycle, while the generic ITuning<T> class will be limited to races between equal types*.

    Chaosfire's point regarding the interface name is still valid.

    *This is a bit over-simplified to make my point clearer. Of course Car could implement ITuning<Car> and ITuning<Motorcycle> but this may not be what you want.