Darla SandyKnowledge Contributor
How do you implement an interface in Java?
How do you implement an interface in Java?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
1. Anonymous Inner Class: You declare and instantiate the class at the same time, providing implementations for the interface methods within the class definition.
“`java
MyInterface obj = new MyInterface() {
@Override
public void method1() {
// Provide implementation for method1
}
@Override
public int method2(String str) {
// Provide implementation for method2
return 0;
}
};
“`
2. Override Methods: As before, you override the interface methods within the anonymous inner class, providing the desired implementations.
“`java
@Override
public void method1() {
// Provide implementation for method1
}
@Override
public int method2(String str) {
// Provide implementation for method2
return 0;
}
“`
3. Use the Object: You can then use the object of the anonymous inner class wherever the interface type is expected, just like with regular implementations.
“`java
obj.method1(); // Invoke method1
int result = obj.method2(“example”); // Invoke method2 and store the result
“`