Lab 3: Classes and Methods

Introduction

In this lab, you're going to explore the concept of Encapsulation. We'll take the department store customer credit account example from last week and refactor it to use two classes, Account and Customer. We'll use encapsulation to control how a developer can access and manipulate the data within our Customer and Account classes.

Part 1: Creating the Classes

We'll start by creating our Customer and Account classes.

The Account class represents a credit account, and has properties of initial balance, credits, and charges. The Account will also have a method for computing and returning the current balance called queryCurrentBalance.

The Customer class contains information for the customer, including their first name, last name, and an Account object representing their credit account.

Part 2: Getters and Setters

Once you have your Account and Customer classes, wrap each of the properties so they are accessed using methods get<property> and set<property>. For example, to get the first name of a customer, you'd use the customer.getFirstName() method to get the first name. Think about what each method will need in order to get and set the properties of each object.

Part 3: Multiple Objects from the Same Class

Create 3 customer objects, each with their own individual accounts.

Templates

/*
 * Account.java
 */


public class Account {
    Double initialBalance;
    Double charges;
    Double credits;
    Double queryCurrentBalance() {
        return initialBalance - charges + credits;
    }
}


/*
 * Customer.java
 */

public class Customer {
    String firstName;
    String lastName;
    Account creditAccount;
}
public class Main {
    public static void main(String[] args) {
        Customer john = new Customer();
        john.setFirstName("John");
        john.setLastName("Doe");
        john.setCreditAccount(new Account());
        john.getCreditAccount().setInitialBalance(0.0);
        john.getCreditAccount().setCredits(500.0);
        john.getCreditAccount().setCharges(250.0);
    }
    
}