Course Content‎ > ‎Session 10‎ > ‎

Implementing an Interface

You use an interface by defining a class that implements the interface by name. When a class implements an interface, it must provide a full definition for all the methods declared in the interface, as well as all of the methods declared in all of the superinterfaces of that interface. A class can implement more than one interface by including several interface names in a comma-separated list of interface names. In that case, the class must provide a full definition for all of the methods declared in all of the interfaces listed, as well as all of the superinterfaces of those interfaces.

Here is an example illustrating the use of interfaces in Java:

    public interface DemoInterface
    {
        static float mul(float x, float y);
        static float divide(float x, float y);
        public final int someConstant = 1.12;
    }
        
    class demo implements DemoInterface
    {
        /* mul is class method, which returns a decimal number, which is the
           product of the two decimal numbers passed to it. */
        static float mul(float x, float y)
        {
            return x * y;
        }
        
        /* divide is class method, which returns a decimal number, which is the
           result of division of  the two decimal numbers passed to it. */
        static float divide(float x, float y)
        {
            return x / y;
        }
        
        public static void main(String args[])
        {
            /* to call a class method, you use dot notation.  You can use either
               an instance of a class or the class name itself to call a class
               method */  
            
            // a1, an object of class demo is declared and created here
            demo a1 = new demo( );  
            
            // class method mul is called using the object a1 of class demo
            float a = a1.mul(32, 4);   
            
            // class method divide is called using the class demo itself
            float b = demo.divide(4, 2); 
            System.out.println(" value of a is = "+ a);
            System.out.println("value of b is = " + b);
            System.out.println("value of constant is = " + someConstant);
        }
    } // end of definition of class demo  

Comments