Sobes.tech
Junior — Middle

How to implement an interface constructor in code?

sobes.tech AI

Answer from AI

In Java and Android, interfaces cannot have constructors because they do not contain implementations and cannot be instantiated directly.

However, if you need to create an object that implements an interface, you create a class that implements this interface, and this class can have a constructor.

Example:

public interface MyInterface {
    void doSomething();
}

public class MyClass implements MyInterface {
    private String data;

    // Class constructor
    public MyClass(String data) {
        this.data = data;
    }

    @Override
    public void doSomething() {
        System.out.println("Data: " + data);
    }
}

Then you can create objects of MyClass and use them as objects of MyInterface:

MyInterface obj = new MyClass("Example");
obj.doSomething();

Thus, the constructor is implemented in the class, not in the interface.