Why does constructor with arg undefine the default constructor? - java

Consider -
public class Class_A {
public void func() {...}
public void func(int a){...}
All three -
Class_A a = new Class_A(); // legal
a.func(); // legal
a.func(1); // legal
But After constructor with arg like public Class_A (int a){...} is added to Class_A , the default constructor become to be -
Class_A a = new Class_A(); // The constructor Class_A() is undefined
Thats force me to add public Class_A() {/*Do Nothing*/} into Class_A .
Since each class has default constructor , why doesn't both default constructor and constructor with arg can exist together just same func() and func(int a) are ?

it has default constructor unless you define your own constructor, in this case you need to re define default constructor

Because If you write a constructor, compiler wouldn't write a default constructor for you. you have to write one explicitly.
From JLS:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.

It's the other way around.
If you don't have any constructor you get the no-arg one by default.

The name "default constructor" implies that it is provided when you don't provide one yourself. As soon as you provide your own constructor, the compiler will not generate a default constructor for you.
Be careful not to confuse the default constructor with the no-arg constructor. These are two entirely different things.

Related

can you use default and parameter constructor at the same time?

I have been assigned to make a class using both default and parameter constructor but the thing is, is that even possible? I don't get how it can even work..both are supposed to assign values to variables
Borrowed from this answer from #bohemian
public class Person
...
public Person() {
this("unknown", 0); // you can call another constructor
}
public Person(String nm, int ag) {
name = nm;
age = ag;
}
...
}
In this example if the no-args constructor is called then unknown and 0 will be passed to the other constructor
When you define another constructor in your class, you do not get the "usual" default constructor (public and without arguments) anymore.
However, you can add it back in:
class MyClass{
MyClass(String param){} // custom constructor
MyClass(){} // bring back the non-arg one
}
Of course, when creating an object instance using new you have to choose which one to call (you cannot have both):
MyClass instanceA = new MyClass("a string");
MyClass instanceB = new MyClass();
The constructors can call each-other (using this(parameters)) or shared methods if there is common functionality in them that you want to keep in one place.
Actually you can't do that in Java, by definition.JLS §8.8.9, http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9 says, "If a class contains no constructor declarations, then a default constructor is implicitly declared." So as soon as you add any constructor declaration, even a no-arg constructor, you don't get a default constructor.

Does a subclass in Java need a constructor if there is one for the superclass? [duplicate]

What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
Neither of them. If you define it, it's not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
This is exactly the same as
public Module()
{}
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
Reference: Java Language Specification
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
the question got the defaults wrong, and
the constructor has exactly the same effect whether they are included or not.
A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()
public Module(){
}
A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.
Per The Java Language Specification Third Edition:
8.8.9 Default Constructor
If a class contains no constructor
declarations, then a default
constructor that takes no parameters
is automatically provided...
Hi. As per my knowledge let me clear the concept of default constructor:
The compiler automatically provides a no-argument, default constructor
for any class without constructors. This default constructor will call
the no-argument constructor of the superclass. In this situation, the
compiler will complain if the superclass doesn't have a no-argument
constructor so you must verify that it does. If your class has no
explicit superclass, then it has an implicit superclass of Object,
which does have a no-argument constructor.
I read this information from the Java Tutorials.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
As per the docs
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Example
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
public class Dog{
public Dog() {
}
}
and when you create it's object
Dog myDog = new Dog();
this default constructor is invoked.
default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.
If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.
E.g.
class Klass {
// Default Constructor gets generated
}
new Klass(); // Correct
-------------------------------------
class KlassParameterized {
KlassParameterized ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassParameterized(); //// Wrong - you need to explicitly provide no-arg constructor. The compiler now never declares default one.
--------------------------------
class KlassCorrected {
KlassCorrected (){ // No-arg Constructor
/// Safe to Invoke
}
KlassCorrected ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassCorrected(); /// RIGHT -- you can instantiate
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
In your case, there is no default constructor as you are adding them programmatically.
If there are no constructors added by you, then compiler generated default constructor will look like this.
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
Purpose of adding default constructor:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.
The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.
Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.
class Module{} // you will never see the default constructor
If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.
This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)
class Module{
Module() {} // this look like a default constructor but in not.
}
A default constructor does not take any arguments:
public class Student {
// default constructor
public Student() {
}
}
I hope you got your answer regarding which is default constructor.
But I am giving below statements to correct the comments given.
Java does not initialize any local variable to any default value. So
if you are creating an Object of a class it will call default
constructor and provide default values to Object.
Default constructor provides the default values to the object like 0,
null etc. depending on the type.
Please refer below link for more details.
https://www.javatpoint.com/constructor

Confusion with explicit constructor invocation

In the code that I have provided the overloaded constructor with argument which makes a call to the no-args constructor, which inturn should call the constructor of the object class in this case. So how does using the this() keyword execute the program correctly but not a direct call to the constructor.
public class S {
S() {
System.out.println("S()");
}
S(int i) {
this();
S();// The method S is undefined for type S
System.out.println("S(int i)");
}
public static void main(String[] args) {
S obj1 = new S();
System.out.println("----------");
S obj2 = new S(10);
System.out.println("----------");
}
}
Syntactically, S() is a method invocation, but you do not have a method called S.
this(); is special syntax for using another constructor in the same class.
To illustrate this point, I added:
void S() {
System.out.println("Method S()");
}
It now compiles, and the output is:
S()
----------
S()
Method S()
S(int i)
----------
A constructor is defined to initialize (construct) objects, therefore you can't call it.
S s = new S();//Correct
S(); //Incorrect, you are calling a method not a constructor.
new S();//Correct
this() is used to to pass arguments to constructor of the same class.
super() is used to pass arguments to parent constructor.
This is called explicit constructor invocation.
Note that when invoking a constructor from another constructor, it must be the first statement of the constructor else it won't compile.
How to invoke other constructors of the same class is defined by The Java Language Specification, section 8.8.7.1 Explicit Constructor Invocations:
• Alternate constructor invocations begin with the keyword this
(possibly prefaced with explicit type arguments). They are used to
invoke an alternate constructor of the same class.
• Superclass constructor invocations begin with either the keyword
super (possibly prefaced with explicit type arguments) or a Primary
expression. They are used to invoke a constructor of the direct
superclass.

Why do we have the output : S1S2 in this case?

In the code below, the output is : S1S2. Why do we get the that result?
public class S1 {
public static void main(String[] args) {
new S2();
}
S1(){
System.out.print("S1");
}
}
class S2 extends S1{
S2(){
System.out.print("S2");
}
}
Since S2 extends S1, it's equivalent to calling all the constructors in a top-level down order.
Java will first create the parent object, S1 and call it's constructor. Then move down to the next object, S2 with it's constructor.
If a derived class's constructor doesn't explicitly call its base class's constructor (via super(...)) then there is an implicit call
super();
to the base class's default constructor in each derived class's constructor.
In the constructor of a subclass, there is an implicit call to the superclass's default constructor.
Here is a quote from the Spec :
If a constructor body does not begin with an explicit constructor
invocation and the constructor being declared is not part of the
primordial class Object, then the constructor body is implicitly
assumed by the compiler to begin with a superclass constructor
invocation "super();", an invocation of the constructor of its direct
superclass that takes no arguments.

Java default constructor

What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
Neither of them. If you define it, it's not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
This is exactly the same as
public Module()
{}
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
Reference: Java Language Specification
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
the question got the defaults wrong, and
the constructor has exactly the same effect whether they are included or not.
A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()
public Module(){
}
A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.
Per The Java Language Specification Third Edition:
8.8.9 Default Constructor
If a class contains no constructor
declarations, then a default
constructor that takes no parameters
is automatically provided...
Hi. As per my knowledge let me clear the concept of default constructor:
The compiler automatically provides a no-argument, default constructor
for any class without constructors. This default constructor will call
the no-argument constructor of the superclass. In this situation, the
compiler will complain if the superclass doesn't have a no-argument
constructor so you must verify that it does. If your class has no
explicit superclass, then it has an implicit superclass of Object,
which does have a no-argument constructor.
I read this information from the Java Tutorials.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
As per the docs
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Example
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
public class Dog{
public Dog() {
}
}
and when you create it's object
Dog myDog = new Dog();
this default constructor is invoked.
default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.
If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.
E.g.
class Klass {
// Default Constructor gets generated
}
new Klass(); // Correct
-------------------------------------
class KlassParameterized {
KlassParameterized ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassParameterized(); //// Wrong - you need to explicitly provide no-arg constructor. The compiler now never declares default one.
--------------------------------
class KlassCorrected {
KlassCorrected (){ // No-arg Constructor
/// Safe to Invoke
}
KlassCorrected ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassCorrected(); /// RIGHT -- you can instantiate
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
In your case, there is no default constructor as you are adding them programmatically.
If there are no constructors added by you, then compiler generated default constructor will look like this.
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
Purpose of adding default constructor:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.
The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.
Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.
class Module{} // you will never see the default constructor
If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.
This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)
class Module{
Module() {} // this look like a default constructor but in not.
}
A default constructor does not take any arguments:
public class Student {
// default constructor
public Student() {
}
}
I hope you got your answer regarding which is default constructor.
But I am giving below statements to correct the comments given.
Java does not initialize any local variable to any default value. So
if you are creating an Object of a class it will call default
constructor and provide default values to Object.
Default constructor provides the default values to the object like 0,
null etc. depending on the type.
Please refer below link for more details.
https://www.javatpoint.com/constructor

Categories

Resources