There is no constructor for interface in Java?

前端 未结 6 587
深忆病人
深忆病人 2020-12-17 06:48

In Java, if I have an interface:

public interface MyInterface{
}

Then MyInterface implementation is:

class MyC         


        
6条回答
  •  生来不讨喜
    2020-12-17 07:29

    You are correct. An interface may not specify a constructor, the constructor gets specified in the class that implements the interface.

    public interface Foo {
        public void doSomething();
    }
    
    
    public class Bar implements Foo() {
        public Bar(int value) {
        }
    
        @Override
        public void doSomething() {
        }
    }
    

    then when you want to use your interface you need to do something like

    Foo foo = new Bar(2);
    

提交回复
热议问题