Java Interface

Advertisements

Interface in Java

Abstract class is used in situation, when we have partial set of implementation of methods in a class. For example, consider a class have four methods. Out of four methods, we have an implementation of two methods and we need to restrict derived class to implement other two methods. In these kind of situations, we should use abstract class.

Interface is used in situation, when we need to restrict derived class to implements all methods. This can be done by making abstract class with all abstract methods, then why use interface? The answer is, a class can inherit only one class at a time but a class can implement more than one interface at a time along with another class.

  • Interface must be declare with interface keyword.
  • Like abstract class, we can't create an object of abstract class.
  • All methods in interface are public and abstract.
  • We must implement all method in derived class.
  • A class can inherit interface using implements keyword.

Example of java interface


//InterfaceDemo.java

    interface inter1
    {
        void Display1();
        void Display2();
    }

    interface inter2
    {
        void Display3();
        void Display4();
    }

    class DerivedClass implements inter1, inter2
    {
        public void Display1()
        {
            System.out.print("\n\tThis is Display1() method of Derived class.");
        }

        public void Display2()
        {
            System.out.print("\n\tThis is Display2() method of Derived class.");
        }

        public void Display3()
        {
            System.out.print("\n\tThis is Display3() method of Derived class.");
        }

        public void Display4()
        {
            System.out.print("\n\tThis is Display4() method of Derived class.");
        }
    }

    class InterfaceDemo
    {
        public static void main(String[] args)
        {
            DerivedClass D = new DerivedClass();

            D.Display1();
            D.Display2();
            D.Display3();
            D.Display4();
        }
    }

    Output:
                This is Display1() method of Derived class.
                This is Display2() method of Derived class.
                This is Display3() method of Derived class.
                This is Display4() method of Derived class.

Advertisement