Wednesday, February 1, 2017

Learn Java for Beginner easily ! Part 16 : Constructors

     What's up guys ! Welcome back to my Java tutorials series. In this tutorial I'm gonna teach you guys about constructors. What a Constructors does is to allow you to initialize a variable as soon as you create a new object (class). Let me guys explain it to you by example. Now I want you guys to type both of the codes below :
1. First Code (Main Class) :



2.Second Code (Another class that being called from the Main Class)


After you guys have type both of codes, I want you guys to run it. Always remember that you have to run your program from where the Main Class belong. As you guys can see that the result is "null" although I didn't type any "null" inside the System.out.println(); keyword. 

Q ; How is that possible ?

A ; Well, that's because there are no any values inside the "backname" variable. That's why java reads       it as a null variable. 

So this is where the Constructors takes its part. With Constructors, you can initialize  the value inside the variable that you are about to used right when you make a new Object (class).To solve the problem of the codes above, you guys are gonna have to build a constructor. Here is how to make it :


The one that I've marked with the blue curly bracket is basically a method called Constructors. So to make a  Constructors, what you're going to do is to make a new method by naming the method as the same name as the class name where your Constructors belong.

Q : So... How to use this Constructors ?

A : First, go to your first class (The first code above). Then fill the parameter with the value you that
      you want. If you are confuse, It is completey okay,just look at the picture below. Don't forget to 
      run the program after you guys have typed it.


As you guys can see, The time I fill the parameter with a value (String) is right when the result of the program changed. Just like I said in the first paragraph,What a Constructors does is to allow you to initialize a variable as soon as you create a new object (class). You guys can also input more than one different values to be excecuted and this is where the Constructors are  very useful, because it's simplier and of course easier ! Here is how to insert more than one value :


See ? It's  totally SIMPLIER right ? you guys only need to copy the line before,paste it in the next line,add a number after the object, then changes the value as how you want it.Maybe in this level of tutorial you guys are not gonna really understand what's the function of Constuctors. But, I'm pretty sure in the higher level of prgrammiung, you guys are gonna get the point.

So that's it guys for now. Thank you guys for visiting my blog, hope you guys enjoy it and see you on the next tutorial. If you guys got something to be asked, please leave a comment below and thank you very much.

Greetings from Programmer !

No comments:

Post a Comment