SheppardDigital
SheppardDigital

Reputation: 3255

Program to interface - but with custom methods on implementation

I recently experienced this problem with an implementation of a class in Spring Boot that I couldn't program to its interface because the methods I'm trying to call on the implementation don't exist on the interface.

I'll simplify the problem; below are an interface and an implementation of that interface:

public interface Vehicle {
    public String beep();
}

public class Car implements Vehicle {
    public String beep() {
        return "BEEP!";
    }

    public String breakDown() {
        return "CRASH BANG WALLOP";
    }
}

If I reference the car as a vehicle, I can't use the breakDown method as it doesn't exist on the interface;

public void test() {
    Vehicle myVehicle = new Car();
    myVehicle.breakDown();
}

Is there a way around this?

For reference, the Spring Boot implementation I was having problems with is the JavaMailSenderImp class which implements the JavaMailServer interface, but I also have custom methods which I can't access when I program to its interface.

Upvotes: 1

Views: 63

Answers (2)

nbrooks
nbrooks

Reputation: 18233

If you know the type of the class implementing the interface you can simply cast to that type:

public void test() {
    Vehicle myVehicle = new Car();
    ((Car) myVehicle).breakDown();
}

Depending on your code, this may cause a warning about an unchecked cast, which you can either suppress directly using @SuppressWarnings("unchecked"), or by using instanceof to verify the type before casting.

Ultimately, though, this points at a problem in your code design; the purpose of interfaces is to abstract the implementation details away from the code using your service, and reduce coupling. If you're coding to an interface, ideally you should be able to swap out implementations in the background without any impact to code interacting with your service.

Upvotes: 2

pulkit-singhal
pulkit-singhal

Reputation: 847

You can always cast the object into specific type and use the custom methods

((Car) myVehicle).breakDown();

Upvotes: 4

Related Questions