Convert Interface to different type

1064 views java
1

How would I convert an interface to another type?

Let's say i have an interface of type 'Cars' and another one of type 'trucks'. I would like to convert this interface to type 'Vehicles'.

How would i go about solving that?

answered question

Why should you want to convert interfaces?

You simply cant.

@B001? because i already have instances of both and would like to get them in one

Interfaces can extend other interfaces so assuming I understand you correctly, just create a new interfaces Vehicle (no plural), move the common method declarations to that new interface and let the other interfaces extend it. Then all classes that implement either of the two also implement the new interface. If you want to get rid of them you then should be able to replace them with the new interface in your code on a per-use basis.

2 Answers

1

You can either:

  1. Change all classes which currently implement Car or Truck to now implement Vehicle instead.

  2. Make Car and Truck extend your new interface Vehicle.

Eg:

If you currently have:

class A implements Car {
    public void carDrive(){ ... }
}

class B implements Truck {
    public void truckDrive(){ ... }
}

You could change it to:

class A implements Vehicle {
    public void vehicleDrive(){ ... }
}

class B implements Vehicle {
    public void vehicleDrive(){ ... }
}

posted this
10

If I understand correctly, you have an interface Vehicle with some methods. And two interfaces Car and Truck with some methods. And you want to also use the methods of the Vehicle in the Car and Truck interfaces?

If that's the case, how about this:

interface Vehicle{
  // Some methods
}

interface Car extends Vehicle{
  // Some methods
}

interface Truck extends Vehicle{
  // Some methods
}

Now if you have a class like this:

class Bmw implements Car{
  // Overwrite methods of both the Cars and Vehicles interfaces
}

posted this

Have an answer?

JD

Please login first before posting an answer.