Java Programming Tutorial – 10 – Adding a Constructor to a Class
- December 25, 2023
- Posted by: MainInstructor
- Category: BASIC C Go Java Real Estate
Video Title: Java Programming Tutorial – 10 – Adding a Constructor to a Class
Hello welcome to this lesson of mastering Java this is lesson number 10 here we’re gonna continue working with classes and objects and we’re going to talk about the concept of the constructor for an object or the constructor for a class definition it’s one of those concepts that when you read
A book on object-oriented programming they’re always gonna start talking about constructors and things and if you don’t have the basic understanding of what an object is or how they work then constructors seem very very unclear very hard to understand but I’m going to show you in about five minutes how easy to
Understand the concept of a constructor really is so first this is less than ten and you see a lot of code here this is a direct cut and pace of lesson nine I basically just highlighted the whole darn thing and I brought it in here because the easiest way to demonstrate
What a constructor is is to really modify what we’ve done so just to show you that this code is fully functional I’m gonna save this and I’m gonna run it and this is basically the output of the last lesson or the last exercise that we did basically we’re calling a method to
Compute some of these values we’re computing or we’re calling the fuel needed method here for our output statement and let’s remind ourselves here here’s the aircraft class we have some member variables here we have two integers and two double values and then we have two methods that we have that we
Have basically used we have defined inside of our class we have one of them called calculate endurance that that guy operates on two of the member variables to calculate how long the airplane can stay in the air in hours and then we have another method that actually takes
An argument in time and basically tells us how many gallons of fuel something an airplane is gonna take if we fly for X number of hours so if we fly for three hours how many gallons of fuel that’s going to take that’s all that’s in our class up till
Now and then up here in the main method we have initialized the object here Cessna and Piper objects and then we have this block here which we’ve been using to basically put the values into the member variables we use the dot notation to put the number of passengers
The speed the number of gallons in the fuel tank in the how many gallons per hour that guy takes and then of course we have the prints Damon’s here which is using one of the methods here alright so that’s enough of an overview that the deal with the
Constructor is I want you to notice how much overhead is required to create this object first or these two objects first of all we have to put this line in which is the class name aircraft and then the object name and then new aircraft and that basically goes and creates a new
Object assigns it to this name reserved memory and so on so the cessna object now contains the variables passengers cruise speed fuel capacity and fuel burn rate when we do the same thing for the piper when we create the object here it again has those same four variables so
Those basically need to have real values put into there so we use the dot notation to put them in there but notice how much space this takes up I mean this is a lot this is a lot to to remember to do to actually initialize all the
Variables and also notice that this is only four variables in our particular class a real class and Java may have a dozen variables or more and so you need to kind of remember to put each one for every single object you create you have to go in here with the dot notation and
Put all of the different values in there don’t put any typos don’t forget to do one of them you have to make sure it’s all right there nothing’s gonna work properly and also just look how much screen real estate in terms of code it takes constructors basically eliminate
The need to do this blue part this highlighted part what we’re going to do is we’re going to add something called a constructor to this class it’s gonna be something we type right in here and it’s gonna tell Java hey when you create an object I want you to initialize these
Variables with values so then whenever we initialize the the object or we instantiate the object whenever we create it up here in this line right here we’ll just pass the four values inside of this parenthesis the passengers the cruise speed the fuel capacity and the burn rate then whenever
The object is created it’ll put those values in here and that’s what a constructor does you think of a constructor or something that’s being built that’s what a constructor does or somebody that builds something well that’s what a constructor for the class is doing it’s putting those values in
And fully forming the object so it’s kind of construct all right so enough talking the way to create a constructor let me go ahead and take this method here and bounce it down basically it’s gonna look like a method but the method name has to be very exact
The method name here or the constructor name has to be aircraft it has to exactly match the name of the class we have all right also you don’t want to put void or integer or anything out in front of it because it’s not really a method that returns anything and it’s
Really not a method exactly in the same way that some of these other methods are so you don’t put a return type in front and the name of the constructor has to exactly match the name of the class that’s how Java knows it’s a constructor
Right and then you go and you put your parentheses and then you have to define to Java what values this constructor is going to take now we know it needs four values because we plan to initialize all four of these variables we also know that it’s going to need two integers and
Two doubles because these are the variables we want to initialize so you need to put some parameters in here just like we’ve done for method so you know integer and you can name the variable in the parameter anything you really want but I’m just going to name it with the
First letter of whatever it is we want to eventually assign it to so I’ll take integer P integer C that’s for cruise speed and then I’ll say double fuel capacity that’s FC in double fuel burn rate if B on and then I’m gonna go and
Hit an open curly brace and hit enter in my closing curly brace is now formed and noticed that whenever I do that all of the red text that was there he noticed the red guy was there trying to warn me whenever the bracket comes back all of that disappears and now Java recognizes
That this is a constructor it knows as a constructor because it’s inside the aircraft class it’s a method with the same name as the name of the class right and there’s no return method out in the front these four values are the four values that this constructor is going to
Accept now inside of here it’s very very simple you just take the variable passengers right which is what you’re trying to assign or try to initialize and you’re gonna set it equal to whatever you this instructor receives the variable P and then cruise speed you’re just going to
Set it equal to the set whatever the second value is which is the the event the value that comes down when we could create the guy that I’m going to hit semicolon and then fuel capacity it’s just gonna equal FC because that’s the name that I’m kind of given whatever the
Third value is here and then fuel burn rate is equal to FB on so this is the constructor I’m gonna go ahead and save it very very simple I think you would agree all you’re doing is you’re giving it a name you’re telling Java that it’s going to accept four values and then
You’re basically assigning those different values to the member variables that we’re trying to initialize all right that’s called a constructor now let me show you how to use the constructor let’s go up to the top notice that once we made those changes our our our object creation doesn’t seem
To work anymore you know fact if you try to run this it’s gonna tell you errors exist in the project so you might say what’s the deal here well what’s going on is the purpose of a constructor is to initialize the object with values whenever you create the object but see
Here whenever you got whenever you have the creation of the Cessna 172 object the way you’re supposed to do it is you’re saying create a new object of type aircraft or of class aircraft now we have to pass the values to the constructor which you can read them
Right off the screen from here that’s why I left them there for comma 140 comma 56 point five comma nine point five and notice that when I do that this red line disappears so basically putting all this stuff in in here inside the constructor allows me to delete all of
This because that’s completely doing the same thing what’s happening is when I create the Cessna 172 object a new object is created of type aircraft and you can almost read this now as almost like a method call that’s what a constructor kind of is it’s almost like
A method right notice that I’ve got sort of method name or the constructor name with set of parentheses with four values so these four values first second third or come down and get passed into the constructor and assign to these parameters here which are then assigned to the member variables notice I don’t
Have any dot notation here because Java knows that whenever I’m creating this object the Cessna 172 object and I’m doing this constructor business that whenever I do these assignments inside of here it has to go into that object that I’m creating which is the cessna object so when I’m assigning P to
Passengers I’m assigning it to the variable for the Cessna object when I’m assigning the crew speed I’m assigning it for the cruise speed object all right now to do the piper it’s exactly the same thing inside of the parentheses it’s 6 comma 201 comma 102.5 comma twenty point five notice when I do
That this all disappears so I can actually delete the Piper Saratoga information and I can go up and just kind of delete this white space here notice how much much cleaner the code looks whenever you’re reviewing this you can easily see okay we’re creating two objects here’s the name of the first
Object and here are the four values that are initializing into that constructor and if I don’t know what these four values are here it’s very easy to go down and look and see okay well one of them is for passenger is one of them’s for cruise being one of them sir fuel
Capacity one of them is for fuel burn rate and I can kind of piece it together and see what’s happening there then when I create the next object I’m just passing different values into the constructor if I want to create a third object or a fourth object or a fifth
Object it’ll be a simple matter of another line for each one of them passing the values into the constructor to fully form the object so let me go ahead and hit run here and you should see all of this down here remain exactly unchanged let me go and hit run here
Notice all the values here are exactly the same now these methods are still working fine I can put different values in for instance for the 1.25 I can put 2.5 six and I can pass this 2.5 six into that method that we’ve created to calculate the number of gallons of fuel
Notice that it’s a different amount of fuel here so everything’s working the method calls are working everything is behaving exactly the same it’s just that they go back to lesson nine for a moment basically we have completely eliminated the need for all of this initialization all of this
Kind of ugly code that just sits before I can actually do anything useful is now wrapped up in a single line in a constructor that is the way you’re going to see most programs written all right so that’s we introduce things a certain way I introduce things this way because
You can understand it and it makes sense but then eventually we get to the point where you see that well really you’re probably gonna see this very most of the time all right now I want to show you a few things about constructors before we go too far notice that the constructor is
Formulated where it assumes that it takes four values first one’s an integer seconds and integer next one’s a double next one’s a double all right so if you accidentally for whatever reason initialize the Cessna object and forgot to put the nine point five at the end so you initialized it like this notice
There’s a red line and when you hover over that it tells you the constructor aircraft is undefined so that is a fantastic safety feature when doing programming because it’s very common when you have lots of objects and lots of code that you might forget to initialize one of the values if let’s go
Back to lesson 9 for a moment if I were doing things this way if I accidentally comment this line out then that the codes still gonna run it may not run well it’s but it’s an error is not gonna be thrown up if I forget to do one of
These guys all right but whenever I forget to put something in a constructor Java knows what to expect here so it’s going to give me an error so it’s gonna kind of force me to initialize things the right way once I have my class set up properly it’s gonna force me to
Initialize it with four items like this all right the next thing I want to show you is again notice that the constructor is expecting integer integer double double so let’s go up here let’s say I accidentally initialize the number of passengers that’s the four there with
4.1 let’s say it’s a typo or let’s say I was doing 4.0 right because it’s four petal four people right notice how everything is ready yet so that’s an error when you hover over it the aircraft constructor is undefined because it’s trying to telling you tell you that there’s a problem there’s a
Mismatch in the constructor I’m expecting two integers to be the first two values but here I’m trying to pass it a decimal that’s not going to work because that 4.0 would need to be assigned into an integer called P and that’s just not gonna work that’s what that error is coming from so
Constructors serve a lot of purposes the first one is it cleans up your code and it makes it more readable the second one is it actually prevents you from creating coding errors because once you set your class up with your constructor you have to initialize everything
Properly or it’s just not gonna work now the last thing I want to tell you is let me go and save this the last thing I’m going to tell you is we have talked about how we have a constructor here and this constructor is called aircraft
Which is the same name as the class and we’re saying that it takes four values now that you know that this is a constructor and that these are the four values let me go back to lesson 9 for a minute let’s kind of revisit what we’ve been doing previously when we created
The objects previously this was the line that created the object and then we populate the values into the member variables right but here I think you can kind of see now now that you can kind of sort of kind of look at constructors as methods that just assign values into the
Variables you can see that this is almost like a method call with no parameters in here nothing passed to it so I guess the thing to tell you is that whenever you look at classes in Java okay even if you do not define the constructor there’s always going to be a
Constructor in the background in Java C in this particular case in this old version of the class we had the class definition we have we had this method and we had this method we did not have a constructor here all right so if you don’t list an explicit constructor then
When you call this create the new object you’re basically calling an invisible constructor with the name aircraft that’s just not printed here Java kind of creates it for you and when it does is that constructor is not written here but if you don’t provide one what that
Does is it puts zeros into these values here it puts default values into your member variables so for numeric values it’s going to put a zero inside of there so what I guess what I’m trying to tell you is that even if you don’t specify a constructor and like what we were doing
Before when you create the object Java is doing the initialization of kind of a default constructor behind the scenes and then just populating those variables with real values later now contrast that with this when we specify our own constructor this is the constructor that is then
Used and that’s why we need to pass these values because we’ve kind of defined that template down there and the constructor to tell it what to expect all right so very important lesson on constructors is something you’re gonna run into an object oriented programming quite a bit make sure you understand how
They’re formed what they do basically it’s the same name of the class no return type out in front and then you have what like a method like parameters you specify what it accepts and then you assign the variables in there I hope you can see how easy it makes your code
Readable how clean it looks and why they’re really used so much so kind of get used to this idea and then follow me on to the exercises go ahead and try to do that exercise we’ll be working with the grocery-store class again and creating a constructor for that
Situation so we’ll try to do that yourself and then you can see how I’ve done it and see how your methods compare so make sure I understand this then follow me on to the next lesson in mastering Java we’re continuing to learn how to do this stuff step by step which
I think’s the easiest way to learn anything especially programming where everything is done in a step-by-step fashion
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
I wish my Java professor could explain these concepts how you are doing on your channel! In colleges, professors would throw in complicated examples to clarify simple concepts. Your examples are simple to clarify complex concepts! Thank you, Sir!
Excellent explanations. Thanks!
My best teacher. I am still waiting for python tutorials from you.
A second to appreciate this man. Really great explanation
This video series, finally, FINALLY made java make sense to me. This man is an amazing teacher. And he also is a spectacular engineer – he was flight controller for many Space Shuttle missions. What a delight and life saver these videos are.
amazing !
The way you explain difficult concepts in simplified english is beautiful! That's an amazing skill you have.
Best of the best teachings
I saw this codes in my module but they dont explain it so luckily i foun this xD
good teacher 🙂
Oh my god… I'm starting to really understand all this…
So helpful 😇😁😁
So clear Explanation. Excellent teaching. I am a first-time JAVA learner. Until I saw your video I never understand what methods and constructors are. Keep it up.
thank you so much this clears up so much for me😁
Bro THANK YOU SO MUCH! This saves me from my professor's almost one hour video!
Dude, you have a gift. Thank you so much.
you explained way better than my profs good work bro
you are an excellent teacher, thank you
God bless you !!! thank you so much
This video saved my life. My lectures are in German and my German is not that great, thankfully this video helped me understand what was in my lecture, Thanks a lot!!
Your explanation is awesome.
For more visit: https://youtu.be/wbrWpt–cgw
This has helped me far more than any school lesson in my life. They always opt for teaching all of these concepts at once – constructors, methods, etc… And it's just WAY too much to comprehend and handle.
But seeing it broken down piece by piece, I truly understand it for the first time. We're all lucky to have someone like you who is so methodical and explanatory at every step of the way.
Thank you, from the bottom of my heart. I figured I was going to end up quitting programming because for years, I couldn't understand the single most important aspect of it… I figured I simply wasn't smart enough to keep up with all the people that understood it. But now, I have so much hope and excitement for the future!
Seriously, your teaching method is amaazing!!!!!!!
you are awesome! best explaining I have ever watched! ☺️
I love your way to explain the lesson
you are great
After spending hours bleeding over a textbook and still not understand, your videos are doing more for me than college classes, books, and professors!!! Humbly speaking to everyone. Let's support him by purchasing a few of his courses, which by the way are dirt cheap!!! Say love but also show love!!!!!!
Finally, this has been boggling me for months and now I get it