Default constructors and inheritance in Java

JavaInheritanceInitializationDefault Constructor

Java Problem Overview


I have a question about default constructors and inheritance in Java.

Generally, if you write a class and do not include any constructor, Java provides automatically for you a default constructor (one without parameters), which initializes all instance variables of the class (if there are any) with some default values (0, null, or false). If you write a constructor, however, with some parameters, and you don't write any default constructor, then Java does not provide a default constructor. My question is: what is the case with classes, which inherit from other classes - if I write a constructor with some parameters in them, but don't include a default constructor, do they inherit the default constructor of the super class?

Java Solutions


Solution 1 - Java

  1. If you do not make a constructor, the default empty constructor is automatically created.

  2. If any constructor does not explicitly call a super or this constructor as its first statement, a call to super() is automatically added.

Always.

Solution 2 - Java

Constructors are not inherited.

Also, the initialization of fields is done by the virtual machine, not the default constructor. The default constructor just invokes the default constructor of the superclass, and the default constructor of Object is empty. The good point of this design is that there is no way to ever access uninitialized fields.

Solution 3 - Java

Unless you use super(...) a constructor calls the empty constructor of its parent. Note: It does this on all you classes, even the ones which extend Object.

This is not inheriting, the subclasses don't get the same constructors with the same arguments. However, you can add constructors which call one of the constructors of the super class.

Solution 4 - Java

The basic rule is a call (or invocation) to a constructor should be the first statement that JVM needs to execute,

So when you have a super class with only parameterized constructor and no default constructor, and base class has no explicit call to the parameterized constructor of the super class, JVM provides the super(); call which throws error as there is no default constructor for the super class, so either we provide a default constructor in the super class or we explicitly call the parameterized constructor of the super class in the base class constructor. when we give the explicit call, then JVM doesn't bother to put the line super(); as constructor invocation should be the first statement of the method, which cannot happen (because of our explicit call).

Solution 5 - Java

Section 8.8.9 of the Java Language Specification explains in details what is going on:

> If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

> - The default constructor has the same accessibility as the class (§6.6). > - The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3). > - The default constructor has no throws clauses. > - If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

You can see that there is no inheritance going on here: all there is to it is the "compiler magic" with implicitly declared default constructor. The specification also makes it clear that the default constructor is added only when the class has no constructors at all, meaning that the answer to your question is "no": once you give a class a constructor, the access to the default constructor of its superclass is lost.

Solution 6 - Java

If you provide a constructor then Java will not generate you a default empty constructor. So your derived class will only be able to call your constructor.

The default constructor doesn't initialize your private variables to default values. The proof is that it's possible to write a class that doesn't have a default constructor and has its private members initialized to default values. Here's an example:

public class Test {

	public String s;
	public int i;
	
	public Test(String s, int i) {
		this.s = s;
		this.i = i;
	}
	
	public Test(boolean b) {
		// Empty on purpose!
	}
	
	public String toString() {
		return "Test (s = " + this.s + ", i = " +  this.i + ")";
	}
	
	public static void main (String [] args) {
		Test test_empty = new Test(true);
		Test test_full = new Test("string", 42);
		System.out.println("Test empty:" + test_empty);
		System.out.println("Test full:"  + test_full);
	}
}

Solution 7 - Java

Thumb Rule is that Sub Class should call any constructor from the base class. so if you don't have the default const the call the existing one from sub class. other wise implement the empty const in the base class to avoid the compilation problem

Solution 8 - Java

The answer to your question is very simple. Implicitly(Invisible), the first statement in any constructor is 'super();' i.e. the call to super class's no parameter constructor, until you change it explicitly to something like 'this();','this(int)','this(String)','super(int)','super(String)' etc. 'this();' is current class's constructor.

Solution 9 - Java

When we don't create a constructor Java creates a default constructor automatically. But when we create one or more custom constructors with arguments, Java doesn't create any default constructors. If we create one or more constructors and we want to create an object without any constructor arguments, we have to declare a empty constructor.

Solution 10 - Java

There will be compile time error...because Compiler looks for default Constructor he Superclass and if its not there...its an error...and program will not Compile...

Solution 11 - Java

Any constructor in subclass will call the no argument contructor(or default constructor) of parent class. if you define a parameterized constructor in parent class then you have to explicitly call the parent class constructor with super keyword else it will give the compilation error.

class Alpha 
{ 
  	Alpha(int s, int p) 
	{ 
		System.out.println("base");
    }
  	
} 

public class SubAlpha extends Alpha 
{ 
	SubAlpha() 
	{ 
        System.out.println("derived"); 
	} 
	public static void main(String[] args) 
	{ 
		new SubAlpha(); 
	} 
}

The above code will give the compilation error:

prog.java:13: error: constructor Alpha in class Alpha cannot be applied to given types;
	{ 
	^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

The above error occurred because neither we have any no argument constructor/default constructor in parent class nor we are calling the parameterized constructor from sub class.

Now to solve this either call the parameterized constructor like this:

class Alpha 
{ 
  	Alpha(int s, int p) 
	{ 
		System.out.println("base");
    }
  	
} 

public class SubAlpha extends Alpha 
{ 
	SubAlpha() 
	{ 
        super(4, 5); // calling the parameterized constructor of parent class
        System.out.println("derived"); 
	} 
	public static void main(String[] args) 
	{ 
		new SubAlpha(); 
	} 
}

Output

base
derived

or

define a no argument constructor in parent class like this:

class Alpha 
{ 
  	Alpha(){
    
    }
  	Alpha(int s, int p) 
	{ 
		System.out.println("base");
    }
  	
} 

public class SubAlpha extends Alpha 
{ 
	SubAlpha() 
	{ 
        System.out.println("derived"); 
	} 
	public static void main(String[] args) 
	{ 
		new SubAlpha(); 
	} 
}

output

derived 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser42155View Question on Stackoverflow
Solution 1 - JavapaulmurrayView Answer on Stackoverflow
Solution 2 - JavastarblueView Answer on Stackoverflow
Solution 3 - JavaPeter LawreyView Answer on Stackoverflow
Solution 4 - JavaAbhishek NairView Answer on Stackoverflow
Solution 5 - JavaSergey KalinichenkoView Answer on Stackoverflow
Solution 6 - JavaEmmanuel RodriguezView Answer on Stackoverflow
Solution 7 - JavaMuthu NView Answer on Stackoverflow
Solution 8 - JavaashView Answer on Stackoverflow
Solution 9 - JavaThusithaView Answer on Stackoverflow
Solution 10 - JavaShubhamhackzView Answer on Stackoverflow
Solution 11 - JavaAnmol MiddhaView Answer on Stackoverflow