From the course: Oracle Java Foundations

Unlock this course with a free trial

Join today to access over 24,000 courses taught by industry experts.

Constructor

Constructor

(gentle music) - [Joe] Here, we'll take a look at initializing objects using a constructor method. When we create a new object, one of the things we need to do is potentially initialize values for the internal variables. For example, here we have public class Clothing and it has a description and a price. Now, right now, if we create a new Clothing object, then the description will be null and the price will be 0, because they're not initialized to anything. So typically what you do when you get started is you create the new Clothing object, have the object reference in item1, and then call item1.setDescription, item1.setPrice, et cetera, et cetera, et cetera. Now, as a convenience method, you can actually do all of that at the time you instantiate the object. This is using a method called a constructor. A constructor is a special method that's called just once at the time the object's created, and it's extremely good for initialization and housekeeping in the object as the object's…

Contents