Java Program to demonstrate Interfaces

Program

interface IntDemo
{
    void display();
    void fun();
}
abstract class AbsDemo implements IntDemo
{
	int y = 20;
	abstract void show();
	public void display()
	{
		System.out.println("Implementing display method of interface IntDemo");
	}
	public void fun()
	{
		System.out.println("Implementing display method of interface IntDemo");
	}
	AbsDemo()
	{
		System.out.println("This is constructor of Abstract Class");
	}
}
public class InterfaceDemo extends AbsDemo
{
	InterfaceDemo()
	{
		System.out.println("Constructor of InterfaceDemo Class");
	}
	void show()
	{
		System.out.println("Method inherited from AbsDemo Class");
	}
	public static void main(String[] args)
	{
		InterfaceDemo intObj = new InterfaceDemo();
		intObj.display();
		intObj.fun();
		intObj.show();
	}
}
  1. Interface: IntDemo

    • Defines two abstract methods: display() and fun().
    • Any class implementing this interface must provide implementations for these methods.
  2. Abstract Class: AbsDemo

    • Implements the IntDemo interface, providing concrete implementations of the display() and fun() methods.
    • Has an abstract method show(), which must be implemented by any subclass of AbsDemo.
    • Contains a constructor AbsDemo() that prints a message when an object of its subclass is created.
    • Defines an integer field y = 20.
  3. Concrete Class: InterfaceDemo

    • Extends the abstract class AbsDemo.
    • Provides an implementation for the abstract method show() from AbsDemo.
    • Contains a constructor that prints a message when called.
    • main() method:
      • Creates an instance of InterfaceDemo, which calls the constructors in the inheritance hierarchy.
      • Calls the display(), fun(), and show() methods.

When the program is executed, the following sequence of events occurs:

  1. The InterfaceDemo object is created.
    • The AbsDemo constructor is called first because it is the parent class, and the message "This is constructor of Abstract Class" is printed.
    • The InterfaceDemo constructor is called next, printing "Constructor of InterfaceDemo Class".
  2. The display() method is called on the InterfaceDemo object.
    • The method is inherited from AbsDemo, and it prints "Implementing display method of interface IntDemo".
  3. The fun() method is called on the InterfaceDemo object.
    • Similar to display(), it is inherited from AbsDemo and prints "Implementing display method of interface IntDemo".
  4. The show() method is called on the InterfaceDemo object.
    • The method is implemented in InterfaceDemo and prints "Method inherited from AbsDemo Class".

Output 1

This is constructor of Abstract Class
Constructor of InterfaceDemo Class
Implementing display method of interface IntDemo
Implementing display method of interface IntDemo
Method inherited from AbsDemo Class