Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialbrandonlind2
7,823 PointsDo Java classes have a default no argument constructor?
The Java documentation states this "You don't have to provide any constructors for your class, but you must be careful when doing this. 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" after saying all classes have a default constructor, which is a bit confusing can some explain this further for me?
1 Answer
Simon Coates
28,694 PointsA default no-arg is provided ONLY if you don't define a constructor. If you define a constructor with args, then you don't get an automatic no arg. The problem here is that the parent has an explicitly defined constructor with arguments. It doesn't have an explicitly defined no-arg constructor, and doesn't get the automatic one. The subclass may get a free no arg constructor, but that has no idea how to call the only defined constructor on the parent (requiring arguments). I hope this explanation makes sense.
public class Animal {//version 1 - works
//gets a free no argument constructor
}
public class Animal {//version 2- FAILS
public Animal(String aParam)
{
}
//has an explicit constructor - doesn't get a free no argument constructor.
}
public class Rabbit extends Animal {
//gets a free constructor as it has no explicit constructors
}
class Main {
public static void main(String[] args) {
Rabbit r = new Rabbit();
}
}