I have the following classes:
public abstract class ParentClass
{
public ParentClass()
{
throw new RuntimeException(\"An ID must be specified
calling an inherited constructor to instantiate the class?
Constructors are never inherited, and it doesn't really make sense. A constructor just initializes the state in that particular class. You can't expect a constructor of Parent
to initialize the state of Child
class. That's the job of constructor in Child
class only.
So, no you can't do what you are trying to do. And that's not the issue with Spring. That's pretty much fundamental.
Short answer: Constructors are not inherited in Java.
From the JLS:
Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
This means you have to declare the constructors needed for each subclass and call the corresponding super constructor. Even if it has the same signature it doesn't count as overriding.
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..