Constructor cannot be applied to given types?

前端 未结 3 1466
青春惊慌失措
青春惊慌失措 2021-01-13 15:50

I have the following Java code:

public class WeirdList {
    /** The empty sequence of integers. */
    /*ERROR LINE */ public static final WeirdList EMPTY =         


        
相关标签:
3条回答
  • 2021-01-13 16:40

    You would need to add a no-arg constructor to WeirdList explicitly as EmptyList has a default no-arg constructor but it has no constructor in the superclass that it can call.

    0 讨论(0)
  • 2021-01-13 16:48

    When you call any method the call and callie must match parameters and return type. Special case with constructors is if you don't make one the compiler will insert a blank constructor void Weird(){} you can overload a class and have many constructors, the one that will execute is the one with the same signature ie types.what you are trying is to do something built into java already in the LinkedList, Vector, List java class.

    0 讨论(0)
  • 2021-01-13 16:51

    A subclass does not have to have any constructor with "the same number of parameters in the constructor as the superclass", but it does have to call some of its superclass' constructors from its own constructor.

    If the superclass has a no-arg constructor, it is called by default if an explicit call to a superclass constructor is omitted or if the subclass has no explicit constructor at all (as is your case), but since your superclass does not have a no-arg constructor, compilation fails.

    You could add something like this to your EmptyList:

    private EmptyList() {
        super(0, null);
    }
    

    It may also be a better idea to have an abstract superclass that both of your classes inherit from, instead, but that's a choice.

    0 讨论(0)
提交回复
热议问题