“Could not resolve matching constructor” error when passing in constructor-arg for child class

后端 未结 3 1988
别跟我提以往
别跟我提以往 2021-01-17 02:33

I have the following classes:

public abstract class ParentClass
{
    public ParentClass()
    {
        throw new RuntimeException(\"An ID must be specified         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 03:28

    If you do not provide a constructor in your child class,the compiler inserts a no-arg constructor and adds the first line as call to super no-arg constructor So your code becomes :-

    public class ChildClass extends ParentClass {
    
            public ChildClass() {
                super();
            }
        }
    

    Obviously, u have thrown a null pointer exception which may be causing the problem.I suggest you to add a constructor and make a call to super constrcutor which takes String argument:-

    public class ChildClass extends ParentClass {
            public ChildClass(String id) {
                super(id);
            }
    
            @Override
            public void doInstanceStuff() {
                // ....
            }
        }
    

    This should solve all your problems...

    Note:- If you add a argument constructor,the compiler doesn't not add a default constructor for you.

    Now your beans will initialize properly as it will call the string argument constructor. Currently the compiler is providing a default no-arg constrcutor for you which in turn is calling your no arg parent class constructor and is throwing a null pointer exception..

提交回复
热议问题