Back to all lessons


Lesson 15

Objects - training

I. Shopping item

Task 0

Modify code:

  1. Create new ShoppingItem object called "item"
  2. Set name of "item" to "Book"
  3. Set amount of "item" to -20
  4. Print "item" data using "print" method

public class ShoppingItem {

    public String name;
    public int amount;

    public static void main(String[] args) {
        // todo
    }

    public void print() {
        System.out.println("Name: " + name);
        System.out.println("Amount: " + amount);
    }

}
Task 1

Read the snippet below. Find:

  1. private field
  2. constructor
  3. "this" keyword

Can we:

  1. create the object via "new AlwaysPositive()"?
  2. access "number" field?

After this, create:

  1. a method, which will display value of number.
  2. a method, which will allow us to modify value of "number" field


public class AlwaysPositive {
    private int number;
    
    public AlwaysPositive(int number) {
        if (number < 0)
            this.number = -number;
        else
            this.number = number;
        
        System.out.println(this.number);
    }

}
    
Task 2

Modify ShoppingItem:

  1. Disallow modifying fields directly
  2. Create constructor, which sets values of all fields
  3. Create methods, that allow to modify values

Remember about conditions:

  1. Name of a item must be at least 3 letters long
  2. Amount of a item must be at least 0

II. ShoppingBag

Task 3

Create a new class: "ShoppingBag" which has:

  1. an array for ShoppingItem(s)
  2. a method "printItems" which returns nothing
  3. a method "itemByName(String)" which returns a ShoppingItem

Show usage of ShoppingBag in main method.


Task 4

Create a class called "Customer":

  1. Customer has many ShoppingBags
  2. Customer can print all shopping bags and theirs items
  3. Customer has amount of cash (> 0)
  4. Customer can be VIP (tip: true or false)

Don't forget about: private fields, constructor.