If I have a class:
class A { public A() { } }
and another
class B extends A { public B() { } }
is there any way to get B.B()
not to call A.A()
?
To explicitly call the superclass constructor from the subclass constructor, we use super() .
Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.
With super(parameter list) , the superclass constructor with a matching parameter list is called. Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
There is absolutely no way to do this in Java; it would break the language specification.
JLS 12 Execution / 12.5 Creation of New Class Instances
Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:
- Assign the arguments for the constructor [...]
- If this constructor begins with an explicit constructor invocation of another constructor in the same class (using
this
), then [...]- This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using
this
). If this constructor is for a class other thanObject
, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (usingsuper
).- Execute the instance initializers and instance variable initializers for this class [...]
- Execute the rest of the body of this constructor [...]
The closest you can achieve to the desired behaviour is to delegate initialisation normally performed in the constructor to a template method, which you then override in your subclass implementation. For example:
public class A { protected Writer writer; public A() { init(); } protected void init() { writer = new FileWriter(new File("foo.txt")); } } public class B extends A { protected void init() { writer = new PaperbackWriter(); } }
However, as other people have noted this can typically indicate a problem with your design and I typically prefer the composition approach in this scenario; for example in the above code you could define the constructor to accept a Writer
implementation as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With