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 trializzy goldman
12,542 PointsA constructor method is Not required inside of a class.
Being as Constructor methods are not required inside of classes.
Whats the point of this class then? (isn't a class a blueprint and the constructor a factory! if there is no factory why bother having a blueprint?!)?
What is an example of a class without a constructor?
2 Answers
Lee Geertsen
Java Web Development Techdegree Student 16,749 PointsSometimes you make classes without a constructor when using inheritance. In this case we don't want any object to be an instance of shape. But we don't want to rewrite the function toString every time when we make a new class for a shape. So Rectangle and Circle 'extend' the Shape class, this way they have access to the attributes and functions of the parent class. I hope that this answers your question :)
class Shape {
toString () {
return `Shape`
}
}
class Rectangle extends Shape {
constructor (width, height) {
...
}
toString () {
return "Rectangle > " + super.toString()
}
}
class Circle extends Shape {
constructor (radius) {
...
}
toString () {
return "Circle > " + super.toString()
}
}
Steven Parker
231,275 PointsA class might contain a number of data fields and/or methods, but nothing requiring any specific initialization. In that case, no explicit constructor is needed. But every instance still gets all the methods and fields.