In Java, it is very common for two classes to implement the same interface at the same time. An interface defines a set of methods, and the class that implements the interface must provide a concrete implementation of those methods. The following will show how to fulfill this requirement and provide concrete code examples.
sample interface
First, define a simple interface, such as one that represents an animal, which has a methodmakeSound
:
public interface Animal {
void makeSound();
}
1. Method 1: two classes implement the interface separately
This is the most straightforward approach, with each class providing separate implementations of the interface methods.
1.1 Class 1: Dog
public class Dog implements Animal {
@Override
public void makeSound() {
("Dog says: Bark");
}
}
1.2 Class 2: Cat
public class Cat implements Animal {
@Override
public void makeSound() {
("Cat says: Meow");
}
}
1.3 Test code
Next, the implementation of the interface can be demonstrated with the following test code:
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
();
();
}
}
2. Method 2: Use of anonymous inner classes
You can also use anonymous inner classes to implement interfaces if you don't want to create concrete classes.
public class Main {
public static void main(String[] args) {
Animal myDog = new Animal() {
@Override
public void makeSound() {
("Dog says: Bark");
}
};
Animal myCat = new Animal() {
@Override
public void makeSound() {
("Cat says: Meow");
}
};
();
();
}
}
3. Method III: Use of Lambda expressions (for functional interfaces)
If the interface is a functional interface (i.e., an interface with only one abstract method), you can use a Lambda expression to implement it.
3.1 Modifying the Interface to a Functional Interface
In order to use Lambda expressions, the interface can remain unchanged because it is already a functional interface (with only one method).
3.2 Using Lambda Expressions
public class Main {
public static void main(String[] args) {
Animal myDog = () -> ("Dog says: Bark");
Animal myCat = () -> ("Cat says: Meow");
();
();
}
}
4. Summary
With the above three methods, you can see how to make two classes implement the same interface at the same time in Java. Each method has its applicable scenario:
(1)direct implementation of an interface: Applies to standard object-oriented programming.
(2)anonymous inner class (computing): For scenarios where you need to simply implement an interface but don't want to create a concrete class.
(3)Lambda expression: Applies to functional interfaces and allows for cleaner code.