

#Java constructor with only parameters code
It has to be explicitly put in your code if one is required.) ( Super(parameters) can never be called implicitly by the compiler. If it does not find such a constructor in your superclass, it will give you a compiler error. Similary if super(parameters) is called, the compiler will expect your superclass to have a constructor with parameters(number and type of parameters should match). If it does not find any constructor in your superclass without parameters, it will give you a compiler error. If super() is being called (explicitly or implicitly by the compiler), the compiler will expect your superclass to have a constructor without parameters. Now if you do not explicity type super(), (or super(parameters)), the compiler will put in the super() for you in your code.If your class is a base class inheriting from a super class and you do not explicitly define constructors in that base class, not only will a no-argument constructor be created for you (like the above point) by the compiler, but it will also implicitly call the no-argument constructor from the super class. If you don't explicitly define constructors in any class(base class/super class), the Java compiler will create a no-argument constructor for you in that respective class. If you explicitly define constructors in any class(base class/super class), the Java compiler will not create any other constructor for you in that respective class. I will try to delve into all the possibilities: This can get somewhat confusing solely because there can be many possibilities of the availability or existence of constructors in the super class or base class. There are a few things to be noted when using constructors and how you should declare them in your base class and super class. But in case you don't explicitly provide any java will put default constructor super() call as 1st line of each of your sub class constructors and now if you don't have that in superclass then you will get an error. Which ones to call is really your design choice. B()īottom line is that for an object to be created completely constructors of each parent in the inheritance hierarchy must be called. A()Įxplicitly write no args constructor in B and call your super with some default int argument. In your case the default constructor in Class B will try to call default constructor in class A(it's parent) but as you don't have a default constructor in Class A(as you have explicitly provided a constructor with arguments in class A you will not have a default constructor in Class A ) you will get an error.Įither provide no args constructor in Class A. Now it is a rule that each constructor must call one of it's super class constructor. You have not provided any constructor in Class B so a default constructor will be placed. Why default constructor is required(explicitly) in a parent class if it
