ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.