Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an Extended interface function with base Interface reference?

Sorry if my question did not make any sense. I will try to explain it here. Let's say I have a base interface like this :

public interface SimpleInterface {
    public void function1(); 
}

And an extended interface as follows :

public interface ExtendedInterface extends SimpleInterface{
    public void function2();
}

Lets say I have a class which implements ExtendedInterface :

public class Implementation implements ExtendedInterface {

    @Override
    public void function1() {
        System.out.println("function1");
    }

    @Override
    public void function2() {
        System.out.println("function2");
    }
}

Now is there any way I can call function2() when I'm given a base interface (SimpleInterface) which is instantiated with Implementation class, like this:

SimpleInterface simpleInterface = new Implementation();

I know it defeats the purpose of interfaces but it would save me from doing a lot of code changes.

like image 771
jayanth Avatar asked Jun 30 '26 09:06

jayanth


2 Answers

You'd have to cast to ExtendedInterface, basically:

SimpleInterface simpleInterface = new Implementation();
ExtendedInterface extendedInterface = (ExtendedInterface) simpleInterface;
extendedInterface.function2();

Of course, the cast will fail if the object that simpleInterface refers to doesn't actually implement ExtendedInterface. The need to do this is definitely a code smell - it may be the best option available to you, but it's at least worth considering alternatives.

like image 146
Jon Skeet Avatar answered Jul 02 '26 22:07

Jon Skeet


First you should check if the object instance is actually an implementation of Implementation class as that could be the case that more than one classes are implementing this Interface.

You can do it as below:

//Somewhere in the code 
SimpleInterface simpleInterface = new Implementation();

//Now with the variable you can check it as below
if(simpleInterface instanceof Implementation)
Implementation implemenation = (Implementation)simpleInterface;
implemenation.function2();
like image 24
Aman Chhabra Avatar answered Jul 02 '26 22:07

Aman Chhabra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!