![]() We need to avoid such situations somehow. You can only imagine how such a mistake can "go off" when the program is running! no wheels at all), a missing trunk, a cabin made of an unknown material, and above all, an undefined owner. null"!īut seriously, the bottom line is that our program created an object incorrectly: a car with a wheel width of 0 (i.e. Your buyer, who gave up $2 million for the car, obviously won't like being called " Mr. Cabin material: " + bugatti.cabinMaterial + Engine volume: " + bugatti.engineVolume + ". As a result, the program will behave incorrectly: In this situation, a programmer can easily make a mistake and fail to initialize some field. There's one problem: we have 16 fields, but we only initialized 12! Look at the code now and try to find the fields we forgot! Not so easy, huh? Int accelerationTo100km // how long it takes to accelerate to 100 km/h (in seconds) String manufacturerCountry // manufacturer country String cabinMaterial // interior materialīoolean insurance // flag indicating whether car is insured Int seatsInTheCar // number of seats in the car String ownerLastName // last name of ownerīoolean isNew // flag indicating whether car is new ![]() String ownerFirstName // first name of owner We created our car, and set its model and maximum speed.īut the Car object would obviously not have 2 fields in a real project. What in the world are constructors and why are they needed?Let's consider two examples. You just didn't realize it :) We convince ourselves of this later. This may be the first time you're hearing this term, but you've actually already used constructors. ![]() Without exaggeration, we can say you'll use this topic in real life every day! Hi! Today we'll consider a very important topic that concerns our objects. ![]()
0 Comments
Leave a Reply. |