'Accessing the method of a class (which implements an interface), which is not declared in the Interface [duplicate]

I am trying to play around with interfaces and classes and stumbled upon the below scenario.

I have an interface MyInterface with interfaceMethod(), which is implemented by MyClass1 class. MyClass1 implements the interfaceMethod() and also has its own public method myClass1Method().

Now, when I create myClass1Obj1 object for MyClass1 via interface, the myClass1Method() is not accessible (I understand why it's not accessible). I wanted to know if there is way to access the myClass1Method using the myClass1Obj1.

One way to access the myClass1Method() is to create an object of MyClass1 and access the method. I'm more curious to know if myClass1Method() can be accessed via myClass1Obj1.

Below is the code representation of above scenario.

Interface definition

public interface MyInterface {
    void interfaceMethod();
}

Class definition

public class MyClass1 implements MyInterface{

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

    public void myClass1Method(){
        System.out.println("MyClass1.myClass1Method");
    }

    public static void main(String []args){
        MyInterface myClass1Obj1 = new MyClass1();
        myClass1Obj1.interfaceMethod();
        myClass1Obj1.myClass1Method(); // Compile time error - Cannot resolve method 'myClass1Method' in 'MyInterface'

        MyClass1 myClass1Obj2 = new MyClass1();
        myClass1Obj2.myClass1Method();
    }
}


Solution 1:[1]

Try this:

if( myClass1Obj1 instanceof MyClass1 myInterfaceObj )
{
  myInterfaceObj.myClass1Method();
}

For those more traditionally inclined and more daring is this alternative:

((MyClass1) myClass1Obj1).myClass1Method();

More daring, because the second does not perform any checks whether myClass1Obj1 is really an instance of MyClass1, but on the other side with the code we see: what else could it be?

Of course we can have it also without casting:

final var method = myClass1Obj1.getClass().getMethod( "myClass1Method" );
method.invoke( myClass1Obj1 );

As I am lazy, all the recommended error handling is missing here. Not to mention that your compiler and/or IDE will complain about the unhandled exceptions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1