Q:

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

belongs to collection: Java Interface Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 Sample1Sample2Sample3 classes respectively. After that, we called the sayHello() method from created objects and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to implement multiple interfaces in t... >>
<< Java program to create an interface with a data me...