8. Using Objects
Tips!
Java is an object-oriented programming language. This means we can turn any part of our code into an object with its own variables and methods.
For instance, let's create a program containing a shopping cart list with items.
Just like the previous example, this one also uses some methods which are not part of "base Java". That's why our code starts with the import lines to determine where ArrayList and List can be found.
The class ShoppingCartItem
is an object that can hold the data for each item in the shopping list. The constructor ShoppingCartItem(String name, int quantity, float price)
enables us to make an item that has a name, quantity, and price. The method getTotal()
inside the item will return the total cost for the item based on quantity and price.
In the main method, we can now easily create a list with objects of the type ShoppingCartItem
and add a few of them to the list. With a for-loop, we can read all the items inside the list and calculate the total value.
In the System.out.println
two special characters are used for better readable output:
\n
to jump to a new line\t
to insert a tab
$ java UsingObject.java Raspberry Pi 4, 4Gb 1 x 59.95 = 59.95 Euro Micro-HDMI cable 2 x 5.9 = 11.8 Euro Raspberry Pi 4 power supply 1 x 9.95 = 9.95 Euro Total for shopping cart: 81.70000076293945 Euro