CS230 Lab: Define your own Java classes



Lab: Define your own Java classes


Practice with:

  1. user-defined classes and objects in java. Such classes will include:
    • instance variables,
    • constructor(s),
    • instance methods, and
    • a main() method (for testing)
  2. static variables and methods
  3. reading input from the keyboard (Scanner)
  4. testing your code: in main() and with a Driver
  5. writing javadoc

Task 1: The Animal Class

Set up: No need to download code from the server, as you will write it all from scratch today. However, when you complete the prelab tasks, you should upload your lab folder to your cs230 account on the cs server, as it will be your starting point for this lab.

  • Create a new folder on your Desktop, and name it lab2_yourUserName. All files you work on today should be saved in that folder.
  • Start BlueJ, create a new project calle Lab2Projet.
  • Create a new class called Animal. Make sure the class starts with a capital "A".

[PRELAB] Step 1: Define your instance variables

Although there are many properties that one might choose to describe an animal, today we will stick with these:

  • type: the type of animal (e.g. horse, frog, dog, etc)
  • name: the name of the animal (e.g. Tonto, Froggy, Spot, etc)
  • voice: the sound the animal makes (e.g. neigh, ribbitt, bark)
  • canFly : indicates if the animal can fly (true) or not (false)
  • number_legs: the number of legs the animal has

[PRELAB] Step 2: Write a constructor for your Animal class

The job of a constructor is to initialize the values of each instance variables. For your first constructor, you can assume that there are 5 parameters, one for each of the instance variables. For example, here are a couple sample invocations of your constructor:

   /* These are invocations of your constructor */
   Animal doggy = new Animal("dog","Rover","bark",false,4);
   Animal deer  = new Animal("reindeer","Rudolph","hi",true,4);

Note: This syntax should look familiar. Last week in lab, we created Scanner and Random objects using their respective constructors:

    /* Remember these from last week? */
    Scanner scan = new Scanner(System.in);
    Random rand = new Random();

[PRELAB] Step 3: Write a main() method

Write the main() method. Its header always looks exactly the same:

public static void main (String [] args)

In it, create a few Animal objects, by calling the Animal constructor. At this point, this is all you can do.

Compile and run your program. Nothing much should happen, but at least you can be sure that you do not have any errors so far!

Step 4: Write the toString() method

We recommend that you always writing a toString() method early on in the definition a Java class.
This allows you to see the current state of your object and is really useful when debugging. Write the toString() method, in the Animal class, to produce something similar (doesn't have to be exact) to this:

Code in main() Text produced in DrJava Interactions Pane
System.out.println(doggy.toString()); Rover is a dog with 4 legs that cannot fly that says bark.
// Note: toString() call is implicit
Rudolph is a reindeer with 4 legs that can fly that says hi.

Test your code by printing out the Animal objects you created in the main() method earlier.

Step 5: Write some "getter" and "setter" methods methods

A "getter" method simply returns the value of an instance variable.
For your Animal class, these are possible getters:

  • getType()
  • getName()
  • getVoice()
  • getCanFly(), and
  • getNumberLegs().

Write a couple of them. Test them in the main().

Parallel to a "getter" method, a "setter" method allow the user to change the values of an instance variables. Setter methods are always void. Each setter method should take a parameter with the value to assign to a particular instance variable.
For example, the setType() method will take a String parameter and the setCanFly() method will take a boolean parameter.

Write a couple of setters. Test them in the main().

Step 6: Write some more instance methods and test them!

  • tookFlyingLessons(): sets canFly to be true
  • caughtLaryngitis(): sets voice to be silent (empty string)
  • likesToImitateCats(): sets voice to be a cat sound
  • speak(): Prints out the animal's voice three times (for example: meow meow meow)
  • converse(Animal a2) : Returns a String that contains a conversation between two animals. For example:

           Animal a1 = new Animal("dog","lassie","ruff",false,4);
           Animal a2 = new Animal("cow","helga","moooo",false,4);
           a1.setVoice("everyone dance!");


           A conversation between lassie and helga:

           A conversation between lassie and helga:
                everyone dance!
                everyone dance!  

Step 7: Use of static variables

Add a new variable to your program to keep track of the number of animals that have been created at any point. What kind of variable should this be? Does it have to do with a specific instance of an Animal, or not?

Arrange so that every animal that is created by this application, has a unique id. In particular, the first animal should have 1 as its id, the next one 2, etc.

Step 8: Write a driver

Create a new file, named AnimalDriver, to add your testing code. Make sure to reference your static variable(s) from there!

Step 9: Get input from the user: readAndCreateAnimal()

So far the values properties of the Animal objects we have created are "hard-wired" into the constructor. In this step you will get these values from the user through the standard input. Set up a method named readAndCreateAnimal(). In it, ask the user about all the information you need to create an Animal instance. Create the object, and return it from that method.

NOTE: This method is called from within main(), which is static, and therefore it should also be defined as static.

Step 10: Add some javadoc

take a look at the following resource(s):

javadoc from DrJava

javadoc from Oracle

Based on what you read, add some javadoc to your program.

Then, in the BlueJ Editor window, from the drop down menu, in the upper right corner, choose "Documentation". What do you see? Then open the folder that contains your project. Do you see anything new there?

Step 11: Write a second constructor, with fewer parameters

A class can contain multiple constructors, as long as they differ in their signature. Write another constructor that requires that the animal's type and name are provided, but supplies default values as follows: voice is empty, number of legs is 4, and canFly is false.

  Animal a3 = new Animal("dog","lassie");

  >>lassie is a dog with 4 legs that cannot fly that says

Task 2: The BankAccount Class

Write a class, from scratch, to represent a bank account.

Step 1A: Define your instance variables

  • the name of the person who owns the card.
  • accountNumber: A unique identifier number, as every account has a different account number.
  • rate: The annual interest rate earned by this specific account. So, if the account earns 3% yearly, the value of the variable "rate" will be 3. Notice that different bank clients may enjoy different interest rates on their accounts. (Better clients, better interest rates.) However for now, assume that all accounts earn the same interest rate.
  • balance: The current balance of the account

Step 1B: Define lastAccountNumber variable

lastAccountNumber - The last account number assigned to a customer, so far. Account numbers should be assigned sequentially. So, the first customer gets assigned the number 1, the second customer the number 2, etc.
Why do you think it is a good choice for the above two fields to be static (class) variables, as opposed to instance variables?

Step 2: Define a constructor

BankAccount(): The constructor should take only one input, the account holder's name. The balance will initially be 0 and the interest rate will be 1%. How should we initialize the account number? Remember, we need this number to be unique for every account we ever create!

Step 3: Define the instance methods

  1. define toString() - Returns a string representation of a bankAccount object. It should contain the account holder's name, the account number, the balance and the interest rate. Have you noticed how the account number appears on your bank statement? Something like ****567, for example? Have you wondered why? Think about how you could program this behavior. However, you can postpone this feature for later.
    At this point, add some code in your main() method to create and print out a couple of accounts, for testing purposes.

  2. define a couple of getters
  3. define a few useful methods, at this point, like:
    • makeDeposit() - Takes an amount as an input and updates the current balance. Test this method.
    • makeWithdrawal() - Takes a withdrawal amount as a parameter and updates the current balance. How should this method behave if the withdrawal amount is greater than the balance? Can you think of a couple reasonable behaviors? Test this method.
    • accrueInterest() - Calculates the balance monthly, by accruing the monthly interest rate. Remember that the rate is yearly, so the formula for calculating the balance monthly is
                 balance + (balance * (rate / (100 * 12)))

      Test this method in your main().

Setp 4: Testing your BankAccount class

You have been adding some testing code as you were progressing through your programming. That's great! You should be reasonably confident, at this point, that your methods are working as intended.

Here is a bit of my testing output (it is incomplete, but gives an idea of how to get started:

  • Make a new bank account for Chris Martin:
    Bank Account Holder Name: Chris Martin
    Account #: ****568
    Balance: $0.00

  • Deposit $200
    Bank Account Holder Name: Chris Martin
    Account #: ****568
    Balance: $200.00
    interest rate: 1.5%  

Task 3: Turn in your lab (electronically)

Submit your work into your cs230-labs folder. Here is how to upload your lab02 code to the server:

  • Compress your lab02 folder to submit. Control-click on the lab02_userName1_userNamne2 folder, and choose "Compress ", from the pop-up menu.
  • Use Fetch or Cyberduck to navigate back to your home directory, and then go to cs230/cs230-labs.
  • Drag the .zip file from your Desktop into this folder.
  • Make sure you upload the lab into both partners accounts.