Java-Accessing Implementations Through Interface References

Accessing Implementations Through Interface References

You can declare variables as object references that use an interface rather than a class type. Any instance of any class that implements the declared interface can be referred to by such a variable. When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. This is one of the key features of interfaces. The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them.

Test f = new InterfaceTest();
f.call();

Notice that variable f is declared to be of the interface type Test, yet it was assigned an instance of InterfaceTest. Although f can be used to access the call( ) method, it cannot access any other members of the InterfaceTest class. An interface reference variable only has knowledge of the methods declared by its interface declaration.

Program

0

Program Source

interface Test {
    
    void call();
}

class InterfaceTest implements Test {

    public void call()
    {
        System.out.println("call method called");
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Test f = new InterfaceTest();
        f.call();
    }
}

Leave a Comment