Using constructors and getters in Java!

I was recently tasked to do an assignment, where I had to solve it using constructors and getters in Java.

As you can see by the picture in the bottom I succeeded in doing the assignemt. The assignment was about creating an overview, where you are able to see the author, the gender of the author, and lastly his email.

Just below the author information, I had to display the book titles and the number of pages.

How did I begin?

I began with creating the two classes: Author and Books, I then assigned the attributes, name, gender and email to the Author class. I used the private keyword to encapsulate the attributes.

After creating the variables for the assignment, I had to use a constructor. If you don’t know what a constructor is:

The constructor is called when an object of a class is created. It can be used to set initial values for object attributes

https://www.w3schools.com/java/java_constructors.asp

The constructor has to use the attributes we just made, in order for us to start adding input in the test.java class.

As you can see above, I use the “this.” keyword, and I do that because I want to refer back to the original attribute’s name.

Now as seen above, we are ready to give some input to the constructor in the test class.

We’ve instantiated the Author constructor by referring to it as a1 and a2. After that we’ve given the input of the name, the gender and the email of the author.

We head on over to the Book class, and just as seen above, we make some attributes and assign them the private keyword.

Getters in Java

We then write it as public String getTitle and so on.

After writing it up as above, we’re ready to instantiate.

Heading on over to the test.java class, to give input in form of a title and the number of pages.

And just like that we have everything we needed. Now we just need to make it all come together, and look great! And use the right getters at the right time.

We use the a1 instantiation of the constructor class, and use getName in order for us to use the getters that we gave the author, we then make some room using the quotes. And this process keeps going until you every getter is used.

Final result

If you have any problems with constructors and getters, I highly recommend heading over to: https://www.w3schools.com/java/java_constructors.asp https://www.w3schools.com/java/java_encapsulation.asp