Exercise Set 3

Put your solutions under the set3 directory in your repository.

Don't forget to commit your changes locally and then push them up to GitLab.

Ex7

In a file named Circle.java, create a class named Circle. The class should have the features shown in the following UML diagram.

UML representation of Circle class

The default constructor of the class should initialise the radius field to a default value of 1.0. The other constructor should use the value provided as a constructor parameter. You can assume that the class user takes reponsibility for ensuring that this value is valid to use as a radius.

You can reuse code from Exercise 3 to implement getArea and getPerimeter.

In a file named Ex7.java, create a class named Ex7, containing a small program that tests the Circle class. The program should first create a default Circle object, without supplying a value for radius. Then it should create another Circle object, specifying a radius of 3.5. After this, the program should print the area and perimeter of each circle.

Ex8

Create a file named BankAccount.java, containing a class BankAccount. This class should have the features shown in the following UML diagram.

UML representation of BankAccount class

The two constructors allow a bank account to be created by specifying an account number alone or an account number and a balance. When only the account number is provided, the balance field should be initialised to 0.

The deposit method should check the provided amount. If the amount is greater than 0, it should add that amount to balance and return true; otherwise, it should leave the balance untouched and return false.

The withdraw method should also check the provided amount. If the amount is greater than zero and less than or equal to the current balance, it should subtract that amount from the balance and return true; otherwise, it should return false.

Create a class named Ex8, in a file named Ex8.java. This should contain a small program that tests the BankAccount class. It should create a BankAccount object, then attempt to perform a valid withdrawal, then attempt to perform an invalid withdrawal. After each withdrawal attempt, the program should first print a message to indicate whether the attempt was successful, and then print the current balance of the account.