-1

This is what I was aiming to do:

public interface Controller {
    default public Controller(Model model, View view) {
        this.model = model;
        this.view = view;
    }
}

But it doesn't appear to be working. It seems classes aren't able to successfully inherit this default constructor, because member variables aren't allowed within an interface.

Is there a way to achieve what I'm trying to do?

I want all of my controllers to have this constructor.

Blaine Lafreniere
  • 3,451
  • 6
  • 33
  • 55
  • Possible duplicate of [How can I force a Constructor to be defined in all subclass of my abstract class](https://stackoverflow.com/questions/3164334/how-can-i-force-a-constructor-to-be-defined-in-all-subclass-of-my-abstract-class) – Progman Sep 28 '19 at 21:00
  • Also check https://stackoverflow.com/questions/2804041/constructor-in-an-interface and specially https://stackoverflow.com/questions/689474/why-are-we-not-allowed-to-specify-a-constructor-in-an-interface/689488#689488 – Progman Sep 28 '19 at 21:02

2 Answers2

0

A Java interface does not allow constructors inside it's definition, only the name declaration of methods. The use of an interface is to allow other classes (those classes that use your interface), to provide the code inside of that methods that you declare on your interface.

public interface Controller {
    void setController(MyControllerVariable);
    MyControllerVariable getController();
    boolean isController(MyControllerVariable);
}

Note that in the previous code there are no definition of how and what the methods does. You have to implement the definition of the code inside the methods. For example:

public class YourClass implements Controller {
    MyControllerVariable mcv = new MyControllerVariable();

    public void setController(mcv) {
        // Do something interesting here
    }

    public Controller getController() {
        // Do something interesting here
    }

    public boolean isController(mcv) {
        // Do something interesting here
    }
}

If you want to do something with Constructors you must use a Class. For example:

public class Controller{
    Model model;
    View view;

    public Controller(Model model, View view) {
        this.model = model;
        this.view = view;
    }

}

The use of the 'default' keyword in java cannot be used in constructors, so don't use it. The previous code shows what you want to do. As the class has only one constructor, that's the default constructor.

0

Instead of interface, use abstract class with constructor, that you want to be inherited.

public abstract class Controller {
    protected Model model;
    protected View view;
    public Controller(Model model, View view) {
        this.model = model;
        this.view = view;
    }
}
Oleksii Zghurskyi
  • 3,967
  • 1
  • 16
  • 17