Constructors

constructors

Part of: Writing Classes

What a Constructor Does A constructor is a special method whose only job is to initialize a new object's instance variables. It runs automatically when you use new. Two rules define a constructor: - Its name is exactly the class name . - It has no return type : not even void. Calling new Point(3, 4) runs this constructor with startX = 3 and startY = 4, setting the object's x and y. The Default Constructor If you write no constructor at all , Java silently provides a hidden no-argument constructor that leaves every field at its default value. The moment you write any constructor, that free one disappears: If you still want new Point() to work, you must write it yourself. Overloaded Constructors A class may have several constructors as long as their parameter lists differ. This is called overloading : Java picks the matching constructor by the arguments you pass. new Point() runs the first; new Point(5, 2) runs the second. Validating Input Constructors are a good place to guard against bad data: Key takeaways: a constructor matches the class name, has no return type, initializes state, and can be overloaded so objects can be built in different ways.

Challenge: Time Builder