Sobes.tech
Junior — Middle

What is the role and purpose of an interface in programming?

sobes.tech AI

Answer from AI

In programming, an interface is an abstract contract that defines a set of methods that a class must implement. It does not contain implementations, only method signatures.

Role of an interface:

  • Ensures standardization of interaction between components.
  • Allows creating flexible and extensible architectures.
  • Facilitates component replacement and testing.

For example, in Android, an interface can describe an event listener that must implement a method to handle button presses. A class implementing this interface guarantees that the method will be defined.

Example in Java:

public interface OnClickListener {
    void onClick(View v);
}

public class Button {
    private OnClickListener listener;
    public void setOnClickListener(OnClickListener l) {
        listener = l;
    }
    public void click() {
        if (listener != null) {
            listener.onClick(this);
        }
    }
}
What is the role and purpose of an interface in… - sobes.tech