Accessing Implementations Through Interface References

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.

In the following program, calls the topSpeed( ) method via an interface reference variable. Notice that variable spd is declared to be of the interface type Speed, yet it was assigned an instance of Audi. Although spd can be used to access the topSpeed( ) method, it cannot access any other members of the Audi class. An interface reference variable has knowledge only of the methods declared by its interface declaration.

Program

Accessing Implementations Through Interface References output

Program Source

interface Speed {
    
    void topSpeed();
}
class Audi implements Speed {
    
    public void topSpeed()
    {
        System.out.println("Audi : 250 km/h");
    }
}
class Ford implements Speed {
    
    public void topSpeed()
    {
        System.out.println("Ford : 220 km/h");
    }
}
class BMW implements Speed {
    
    public void topSpeed()
    {
        System.out.println("BMW  : 300 km/h");
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Speed spd = new Audi();
        spd.topSpeed();
        spd = new Ford();
        spd.topSpeed();
        spd = new BMW();
        spd.topSpeed();    
    }
}

Leave a Comment