java implicitly creates a default constructor for us in a class, but only if we have not created any parametrized constructor in that particular class, however it is not important to declare a default constructor if there is no use of it in the implementation i.e, if we are providing parameters for each object created for example: the following program does not call default constructor
OUTPUT:
but when we inherit a super class to create some sub class we should keep in mind that every subclass calls super class constructor first, therefore we need to define a default constructor in super class, but if we explicitly call parametrized constructor of super class in the subclass then also there is no need for creating default constructor in super class
Top comments (3)
So first off, the code you are showing is not Java. It might be Grrovy or Kotlin or some other Java-like language that compiles to the JVM. But it is not pure Java.Secondly:
Not true. Calling the superclass's constructor is a choice that you, the developer, makes.
You do not need to define a default constructor unless you actually call the default constructor explicitly.
It is also just bad practice to leave an implicit definition of a constructor. Be explicit. The implicit default constructor is only useful in two cases:
In all other cases, declare your constructor explicitly, even if it does nothing.
The superclass constructor is not called implicitly when a subclass is instantiated. Superclass constructors always need to be called explicitly. Constructors are not inhereted.
Your example code is a too large, it looks like you missed something.
Consider the following:
Contents of
./cons/Sub.java
Contents of
./cons/Super.java
Compile and run:
So if you are getting an error by which a constructor has been called without being defined, then it is because you actually called a constructor without defining it.
Simplify your example code.
And actually state the correct language.@TaiKedzierski
Thank you for your feedback s , I appreciate and value the time you put in here. also, I don't know why you think it is groovy or something else because it is java as i know and i don't groovy and other stuff
yes I agree that Calling the superclass's constructor is a choice but I was referring to the situations when we need member variables of super class, I should have been cautious about mentioning that thank you for putting this in light since I learnt this stuff just recently I felt like sharing but you cleared the thing more for me.
My apologies - I tested the syntax, your code is indeed standard Java, I was wrong.
Java has changed over the years, I have apparently not kept up with the standards.