user3193063
user3193063

Reputation: 41

Casting an unimplemented interface to an object

I have a class with the same methods implemented as the interface

public class MyClass {

String getString(final String stringName) {
//doSomething
    };
}

This is the interface definition -

public interface MyInterface {

String getString(final String stringName);
}

Is it possible to cast the interface to the class object-

MyInterface interace = new MyInterface;
MyClass class = (Myclass) interface;

Upvotes: 2

Views: 147

Answers (1)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

It is not possible to cast the unimplemented class object to the interface type as you would get an ClassCastException at runtime. This is because Java does not support duck typing, it doesn't check whether the method signatures are the same or not.

But you can use java-8 method reference to pass the logic you implemented in the MyClass getString to the interface reference type:

class MyClass {
    String getString(final String stringName) {
        return stringName;
    }
}
interface MyInterface {
    String getString(final String stringName);
}

public static void main(String[] args) {
    //MyInterface  myInterface = (MyInterface)new MyClass(); //java.lang.ClassCastException: class MyClass cannot be cast to class MyInterface
    MyClass clazz = new MyClass();
    MyInterface  myInterface = clazz::getString;
    System.out.println(myInterface.getString("test"));
}

Also you cannot instantiate a interface as you have done in your code.

Upvotes: 1

Related Questions