Is there a way to require a subclass to call super explicitly in it's constructor?

Recommended Answers

All 4 Replies

Make the superclass default constructor private and provide a public constructor that takes a parameter ?

why would you want to? It's called implicitly as is...

@JamesCherrill
I don't need to pass parameters

@jwenting
I actually didn't know this. I thought constructors worked like methods where you need to call super to call what happens in the super class

Thanks for the info :)

Whether you need a parameter isn't the point. This is the only way I know to do what you asked.
Every constructor must start with a call to a superclass constructor (1). If you don't code one the compiler will do it for you and insert a call to super(). It's done to ensure the superclass is fully initialised before you try to do anything in the subclass.
The only way to prevent that is to make super() unavailable, by making it private.
But you still need a call to superclass constructor, and since the no-args constructor is private you have to call a constructor with one or more parameters.

But as Jwenting asked... Why?

(1) Or a call to another constructor of the same class which, in turn, must start with a call to a superclass constructor or another constructor of the same class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.