This question already has answers here:
Java Error: The constructor is undefined
                                
                                    (8个答案)
                                
                        
                                上个月关闭。
            
                    
我想将ConcreteSubject类中的构造函数ConcreteSubject调用为main。我正在尝试与构造函数一起创建数组,该构造函数接受in作为初始化数组的参数。所以我不确定什么丢失/错了。

public class ConcreteSubject extends AbstractSubject {
    public int arySize;

    private AbstractSpy[] spies;

    public ConcreteSubject(int a) {
        arySize = a;
        spies = new AbstractSpy[a];
    }

    @Override
    void notifySpies() {

    }

    @Override
    public void addSpy(AbstractSpy spy) {

    }
}

public class TestSpies {
    public static void main(String[] args) {
        // this is where there is something wrong as it whats another constructor created.
        ConcreteSubject cs = new ConcreteSubject();
        AbstractSpy spy = new ConcreteSpy();
        AbstractSpy[] spies = new AbstractSpy[10];
        cs.addSpy(spy);
    }
}

最佳答案

当您为类创建构造函数时,java不会为您提供默认的构造函数。并使用ConcreteSubject cs = new ConcreteSubject()初始化对象。

有两种解决方案来初始化数组:


在类ConcreteSubject中创建默认构造函数

公共ConcreteSubject(){

}



然后初始化数组

cs.arySize= x //whatever value you want`
cs.spies = new new AbstractSpy[a];



或者您必须像下面这样初始化您的对象:

ConcreteSubject cs =新的ConcreteSubject(x); //您想要的任何值

07-27 13:38