Lecture 3
Lecture 3
Programming
with Java II
Email: [email protected]
Lecture outcomes
• The this reference
• Array of objects
• Passing array of objects to methods
That is, the this reference, used inside a method, refers to the object through which the
method is being executed
Example:
class Person
{
private static int number = 0;
public Person()
{
number++;
}
}
Dr. Mohamed K. Hussein 9
Static Methods
•Associated with the class as a whole and not individual instances of the class.
–Can be called without having an instances (because it’s called through the class
name not a reference/instance name).
double squareRoot = Math.sqrt(9); // ClassName.method()
I. Design a Shopping Cart program. In this task you will complete a class that
implements a shopping cart as an array of items. The Item class models an item one
would purchase. An item has a name, price, and quantity (the quantity purchased).
The file ShoppingCart.java implements the shopping cart as an array of Item
objects. Complete the ShoppingCart class by doing the following:
• Declare an instance variable cart to be an array of Items and instantiate cart in the
constructor to be an array holding capacity Items.
• There should be addToCart method. This method should add the item to the cart and
update the totalPrice instance variable (note this variable takes into account the
quantity).
II. Design a library program. In this task you will complete a class that
implements a Library as an array of Books. The Book class that models a book
one would find the library. A book has a title, price, year, and Author. The
Library.java implements the library as an array of Books objects. Complete the
Library class by doing the following:
• Declare an instance variable library to be an array of Books and instantiate library
in the constructor to be an array holding capacity Items.
• There should be addBook method. This method should add the book to the
library.