Explain with an example how a class implements an interface.
First ,the interface is to be defined. Defining an interface is placing the method signatures. Then these methods are to be overridden in the class that implements the interface.
Example interface QuestionAnswer
{
String answerForQuestion(String qtn);
}
class AnswerForQuestion implements QuestionAnswer
{
String answerForQuestion(String qtn)
{
System.out.println(“The answer is “ + qtn);
}
}
Create an object of the class AnswerForQuestion and invoke the answerForQuestion() method.
AnswerForQuestion afq = newAnswerForQuestion();
afq.answerForQuestion(“Java is a programming language”);
When a class implements an interface, it has to implement the methods defined inside that interface.
This is enforced at build time by the compiler.
interface interfaceA
{
void methodA(int x);
}
class classA implements interfaceA
{
// implementation for methodA and the rest of the class code if any.
}