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();
}
}
-
Interface:
IntDemo- Defines two abstract methods:
display()andfun(). - Any class implementing this interface must provide implementations for these methods.
- Defines two abstract methods:
-
Abstract Class:
AbsDemo- Implements the
IntDemointerface, providing concrete implementations of thedisplay()andfun()methods. - Has an abstract method
show(), which must be implemented by any subclass ofAbsDemo. - Contains a constructor
AbsDemo()that prints a message when an object of its subclass is created. - Defines an integer field
y = 20.
- Implements the
-
Concrete Class:
InterfaceDemo- Extends the abstract class
AbsDemo. - Provides an implementation for the abstract method
show()fromAbsDemo. - 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(), andshow()methods.
- Creates an instance of
- Extends the abstract class
When the program is executed, the following sequence of events occurs:
- The
InterfaceDemoobject is created.- The
AbsDemoconstructor is called first because it is the parent class, and the message"This is constructor of Abstract Class"is printed. - The
InterfaceDemoconstructor is called next, printing"Constructor of InterfaceDemo Class".
- The
- The
display()method is called on theInterfaceDemoobject.- The method is inherited from
AbsDemo, and it prints"Implementing display method of interface IntDemo".
- The method is inherited from
- The
fun()method is called on theInterfaceDemoobject.- Similar to
display(), it is inherited fromAbsDemoand prints"Implementing display method of interface IntDemo".
- Similar to
- The
show()method is called on theInterfaceDemoobject.- The method is implemented in
InterfaceDemoand prints"Method inherited from AbsDemo Class".
- The method is implemented in
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