In Java, you can define multiple constructors in a class by creating methods with the same name as the class and different parameter lists. You can use the super
keyword to invoke a superclass constructor from a subclass constructor.
Here's an example of how to define two constructors in a subclass and invoke the superclass constructor using the super
keyword:
public class SubClass extends SuperClass { public SubClass() { // Invoke the no-arg constructor of the superclass super(); } public SubClass(int value) { // Invoke the one-arg constructor of the superclass super(value); } }uoSrce:www.lautturi.com
In the above example, the SubClass
class extends the SuperClass
class and defines two constructors: a no-arg constructor and a one-arg constructor. The no-arg constructor invokes the no-arg constructor of the SuperClass
class using the super()
statement, and the one-arg constructor invokes the one-arg constructor of the SuperClass
class using the super(value)
statement.
Note that the super()
statement must be the first statement in the constructor body. If you define multiple constructors in a subclass, you must ensure that each constructor invokes the appropriate superclass constructor.
If the superclass does not have a no-arg constructor, you must explicitly invoke a superclass constructor with arguments from the subclass constructor.