1

I have the following classes:

class Vehicle {
    public void Move() {
        System.out.println("Move");
    }
}

class Bike extends Vehicle {
    public void RideOnBackWheel() {}
}

class VehicleWithEngine extends Vehicle {
    public void EngineStart() {}
    public void EngineStop() {}
}

Now, I have to create class Motorbike with the methods from Bike and VehicleWithEngine, but it doesn't works:

class Motorbike extends Bike, VehicleWithEngine {
    private boolean engine = false;

    @Override
    public void EngineStart() {
        engine = true;
        System.out.println("Engine started.");
    }

    @Override
    public void EngineStop() {
        engine = false;
        System.out.println("Engine stopped.");
    }

    @Override
    public void RideOnBackWheel() {
        if(engine) System.out.println("1 wheel");
    }

    @Override
    public void Move() {
        if(engine) System.out.println("Motorbike.move()");
    }
}

Thanks for any help.

Qorn
  • 189
  • 1
  • 1
  • 6

2 Answers2

4

In java you can't inherit from two classes. You must change your Vehicle, Bike and VehicleWithEngine classes to interfaces using implements keyword instead od extends in Motorbike class.

interface Vehicle
{
    default public void Move()
    {
        System.out.println("Move");
    }
}

interface Bike extends Vehicle
{
    public void RideOnBackWheel();
}

interface VehicleWithEngine extends Vehicle
{
    public void EngineStart();
    public void EngineStop();
}

class Motorbike implements Bike, VehicleWithEngine
{
    private boolean engine = false;

    @Override
    public void EngineStart()
    {
        engine = true;
        System.out.println("Engine started.");
    }

    @Override
    public void EngineStop()
    {
        engine = false;
        System.out.println("Engine stopped.");
    }

    @Override
    public void RideOnBackWheel()
    {
        if(engine) { System.out.println("1 wheel"); }
    }

    @Override
    public void Move()
    {
        if(engine) { System.out.println("Motorbike.move()"); }
    }
}
1

It looks like Bike and VehicleWithEngine don't actually have implementations. If so, you can turn them into interfaces and have Motorbike implement both:

interface Bike extends Vehicle {
    void RideOnBackWheel();
}

interface VehicleWithEngine extends Vehicle {
    void EngineStart();
    void EngineStop();
}

class Motorbike implements Bike, VehicleWithEngine {
    // implementations
}

If Bike and Vehicle have stateless implementations (they don't need to directly access member variables), you can turn them into default methods, for example:

interface Bike extends Vehicle {
    default void RideOnBackWheel() {
        // implementation
    }
}

Otherwise it's not possible to extend from two classes. See the linked duplicate.

shmosel
  • 49,289
  • 6
  • 73
  • 138