Search code examples
javainterfaceinstanceconceptual

Creating instances of interface class java


Can someone explain to me what the meaning of creating a variable of an Interface class is?

Specifically, what does the following code mean:

InterfaceA x = (InterfaceA) factory.createFactoryObject(zz.CONST);

I have always thought that an interface (in Java) is simply a collection of method declarations whose functionality is defined by classes implementing an interface. For example if I have an interface:

public interface IMoveBehavior(){
    public void move_Along_X();
    public void move_Along_Y();
    public void move_Along_Z();
}

then the class would use this interface as:

public class ABC() implements IMoveBehavior{
    public void move_Along_X(){
        //do whatever
    }
    public void move_Along_Y(){
        //do whatever
    }
    public void move_Along_Z(){
        //do whatever
    }   
}

So, coming back to

InterfaceA x = (InterfaceA) factory.createFactoryObject(zz.CONST);

I really do not understand what exactly this means conceptually. Could someone explain or point me to a resource where I can educate myself?

Thanks!!


Solution

  • You're seeing a case of Polymorphism, which is one of the core concepts that makes Interfaces useful.

    InterfaceA x = (InterfaceA) factory.createFactoryObject(zz.CONST);
    

    What's happening here is that factory.createFactorObject(zz.CONST); is returning an Object. I don't know precisely what kind of object it is, but if this code compiles and runs successfully, then the object must at least be of a class that implements InterfaceA. As a result, it has implementations for all the methods defined in InterfaceA.

    So you can cast to InterfaceA, and take it as a given that you can use the methods defined in InterfaceA. The underlying JVM is responsible for knowing exactly how those methods were implemented (by the class the Object is instantiated from) and what to do if those methods are called.