Java program to implement the method of an interface in multiple classes

Learn how to implement the method of an interface in multiple classes in Java?
Submitted by Nidhi, on March 28, 2022

Problem Solution:

In this program, we will create an interface with an abstract method. Then we will implement created interface in multiple classes and defined the abstract method.

Program/Source Code:

The source code to implement the method of an interface in multiple classes is given below. The given program is compiled and executed successfully.

// Java program to implement the method of an 
// interface in multiple classes

interface Inf {
  //public and abstract
  void sayHello();
}

class Sample1 implements Inf {
  public void sayHello() {
    System.out.println("Sample1:Hello World");
  }
}

class Sample2 implements Inf {
  public void sayHello() {
    System.out.println("Sample2:Hello World");
  }
}

class Sample3 implements Inf {
  public void sayHello() {
    System.out.println("Sample3:Hello World");
  }
}

public class Main {
  public static void main(String[] args) {
    Sample1 S1 = new Sample1();
    Sample2 S2 = new Sample2();
    Sample3 S3 = new Sample3();

    S1.sayHello();
    S2.sayHello();
    S3.sayHello();
  }
}

Output:

Sample1:Hello World
Sample2:Hello World
Sample3:Hello World

Explanation:

In the above program, we created an interface Inf with an abstract method sayHello(). Then we defined the sayHello() method in 3 different classes by implementing the Inf interface using the "implements" keyword.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the objects of the Sample1, Sample2, Sample3 classes respectively. After that, we called the sayHello() method from created objects and printed the result.

Java Interface Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.