Inheritance Practice Assignments

Overview

Inheritance is one of the foundations of object-oriented programming. It is a very useful way to reuse and organize classes.

Submission Instructions

Submit each of the following practice assignments at codePost.io. To register for a free codePost account, please follow these instructions.
Watch this short video for a demonstration of submitting an assignment and reviewing the results:
YouTube video: codePost: Submission and Checking Results Thumbnail
Note, currently, feedback is not visible in Safari.

Practice Assignments

Inheritance Hierarchy

Given the following classes, arrange them into an appropriate inheritance hierarchy (by just adding a Java keyword and a class name). Note, you do NOT need to add fields nor methods to any of these classes. Save each class in it's own file (e.g., the BakeryItem class in BakeryItem.java). Submit all of the files.
public class BakeryItem{
    /* fields and methods omited for brevity */
}
public class FoodItem{
    /* fields and methods omited for brevity */
}
public class FrenchBreadItem{
    /* fields and methods omited for brevity */
}
public class FruitItem{
    /* fields and methods omited for brevity */
}
public class ProduceItem{
    /* fields and methods omited for brevity */
}

Circle Class

Shape.java
/**
 * Defines a basic shape with just area
 *
 * @author Hyrum D. Carroll
 * @version 0.3 (3/23/2022)
 */
public class Shape{
    private double area;

    public Shape(){ area = 0.0; }
    public Shape( double a ){ area = a; }
    public void setArea( double a ){ area = a; }
    public double getArea(){ return area; }
    public String toString(){
        return "Shape:\n\tarea: " + area + "\n";
    }
}
ShapeDriver.java
/**
 * Create a simple Circle object
 *
 * @author Hyrum D. Carroll
 * @version 0.2 (10/12/2020)
 */
public class ShapeDriver{
    public static void main( String[] args ){
	Circle cir = new Circle( );
	cir.setRadius( 5.0 );
	System.out.println( cir.toString() );
    }
}
Given the code above, write a Circle class (and save it in a file named Circle.java) that inherits from the Shape class. Include in your Circle class, a single private field double radius. Also include a method void setRadius(double r) (which also sets area) and a method double getRadius() (which also returns the current radius). Change the accessibility modifier for area in the Shape class to be more appropriate for a base class. Make sure that ShapeDriver's main() method executes and produces the following output (underlined text is required for test cases):
Shape:
	area: 78.53981633974483
	radius: 5.0
Submit both your Circle.java and your Shape.java files. Note, the ShapeDriver.java file should not be changed and is already uploaded into the submission system.

Bank Accounts 01: Child Classes

Copy the following SimpleBankAccount class and use it as a base class:
SimpleBankAccount.java
/**
 * Simple representation of a bank account
 *
 * @author Hyrum D. Carroll
 * @version 0.5 (10/12/2020)
 */

import java.text.NumberFormat;

public class SimpleBankAccount{
    // fields (instance variables)
    private double balance;
    private String accountId;

    /**
     * Constructor for objects of class SimpleBankAccount
     */
    public SimpleBankAccount(){
        balance = 0.0;
        accountId = "";
    }

    /**
     * Constructor for objects of class SimpleBankAccount
     */
    public SimpleBankAccount( double bal, String id ){
        balance = bal;
        accountId = id;
    }

    /**
     * Add money to the balance
     *
     * @param  amount the amount to deposit
     * @return void
     */
    public void deposit( double amount ){
        balance += amount;
    }

    /**
     * Remove money from the balance
     *
     * @param  amount the amount to withdraw
     * @return true (success) or false (failure)
     */
    public boolean withdraw( double amount ){
        if( balance - amount >= 0 ){
            balance -= amount;
            return true;
        }else{
            return false;
        }
    }

    /**
     * Get the balance
     *
     * @return the balance
     */
    public double getBalance(){
         return balance;
    }

    /**
     * Set account ID
     *
     * @param the account ID
     */
    public void setAccountId(String id){
         accountId = id;
    }


    /**
     * Get the account ID
     *
     * @return the account ID
     */
    public String getAccountId(){
         return accountId;
    }

    /**
     * Produces a string represenation of the balance
     * @return The balance (with a label)
     */
    public String toString( ){
        // display balance as currency
        String balanceStr = NumberFormat.getCurrencyInstance().format( balance );
        return "Balance for account " + accountId + ": " + balanceStr + "\n";
    }
}
Include at least two classes: CheckingAccount and SavingsAccount. Save your CheckingAccount class in a file named CheckingAccount.java and your SavingsAccount class in a file named SavingsAccount.java. Your CheckingAccount class needs to add a field to track the last processed check number. Also include both a no-argument constructor and a constructor that takes a double for the balance and a String for the account ID. Furthermore, include the following method:
public boolean processCheck( int checkNum, double amount );
which returns false if checkNum has the same check number as the last check processed, otherwise it reduces the balance by amount and returns true.
Your SavingsAccount class needs to have a field for the interest rate. Also include both a constructor that just takes no arguments and a constructor that takes a double for the balance, a String for the account ID and a double for the interest rate (in that order). Furthermore, include an applyInterest() method that multiples the current balance by the interest rate, and adds that to the balance.
The following code should work and produce the output below:
AccountsDriver.java
/** 
 * Exercises the basic functionality of a Checking and SavingsAccount
 *
 * @author Hyrum D. Carroll
 * @version 0.3 (10/12/2020)
 */
public class AccountsDriver{
    public static final double INTEREST_RATE = 0.01;  // 1%

    public static void main( String[] args ){
        CheckingAccount checking = new CheckingAccount( 100.0, "checking123" );
        SavingsAccount savings = new SavingsAccount( 1000.0, "savings124", INTEREST_RATE );

        double monthlyExpenses = 756.34;
        int electricBillCheckNum = 2123;
        double electricBill = 60.34;
        int registrationCheckNum = 2124;
        double registration = 50.00;
        double dinnerMoney = 55.32;
        double futureCar = 200.0;
        double textbook = 90.0;

        // checking account transactions
        checking.deposit( monthlyExpenses );
        checking.processCheck( electricBillCheckNum, electricBill );
        checking.withdraw( dinnerMoney );
        checking.processCheck( registrationCheckNum, registration );
        System.out.print( checking.toString() );
        System.out.println( );

        // savings account transactions
        savings.deposit( futureCar );
        savings.applyInterest( );
        savings.withdraw( textbook );
        System.out.print( savings.toString() );
        System.out.println( );
    }
}
Output (underlined text is required for test cases):
Checking Account:
Balance for account checking123: $690.68
Last processed check number: 2124

Savings Account:
Balance for account savings124: $1,122.00
APR: 1.0%

Make just the necessary changes to the code in SimpleBankAccount to complete the instructions.
Submit the following files:

Hint

Look at the code in SimpleBankAccount's toString() method as an example of how to display two decimal places every time (and not just round to two decimal places).

Bank Accounts 02: Overriding 1

Building off of the Bank Accounts 01 practice assignment above, in your CheckingAccount and SavingsAccount classes, override the toString() method. Additionally include a call to SimpleBankAccount's toString() method. Use the appropriate annotation to designate that you're expecting this method to override another method.
Submit the following files:

Bank Accounts 03: Overriding 2

Building off of the Bank Accounts 01 practice assignment above, add an equals() method that returns true if all of the fields match and false otherwise. The Object class has the following method:
public boolean equals( Object obj )
To override this method, you must have the same method header. Additionally, to use the fields of the class that overrides the method, you need to cast the parameter to the current class.
Your equals methods should work so that the following code will execute, but not display anything:
BankAccounts03.java
/** 
 * Exercises equals()
 *
 * @author Hyrum D. Carroll
 * @version 0.1 (10/12/2020)
 */
public class BankAccounts03{
    public static final double INTEREST_RATE = 0.01;  // 1%

    public static void main( String[] args ){
        CheckingAccount checking = new CheckingAccount( 100.0, "checking123" );
        SavingsAccount savings = new SavingsAccount( 1000.0, "savings124", INTEREST_RATE );

        CheckingAccount checkingCopy = new CheckingAccount( 100.0, "checking123" );
        SavingsAccount savingsCopy = new SavingsAccount( 1000.0, "savings124", INTEREST_RATE );

        if( checking.equals( checkingCopy ) == false ){
            System.err.println("ERROR: The following objects are equal:");
            System.err.println( checking );
            System.err.println( checkingCopy );
        }

        if( savings.equals( savingsCopy ) == false ){
            System.err.println("ERROR: The following objects are equal:");
            System.err.println( savings );
            System.err.println( savingsCopy );
        }

        int electricBillCheckNum = 2123;
        double electricBill = 60.34;
        double futureCar = 200.0;

        checking.processCheck( electricBillCheckNum, electricBill );

        savings.deposit( futureCar );
        savings.applyInterest( );

        if( checking.equals( checkingCopy ) == true ){
            System.err.println("ERROR: The following objects are NOT equal:");
            System.err.println( checking );
            System.err.println( checkingCopy );
        }

        if( savings.equals( savingsCopy ) == true ){
            System.err.println("ERROR: The following objects are NOT equal:");
            System.err.println( savings );
            System.err.println( savingsCopy );
        }
    }
}

Submit the following files:

Shape2D

Write the following four classes to practice using an abstract class and polymorphism. Submit all four classes.

Shape2D class

For this class, include just an abstract method name get2DArea() that returns a double.

Rectangle2D class

Make this class inherit from the Shape2D class. Have it store a length and a width as fields. Provide a constructor that takes two double arguments and uses them to set the fields. Note, the area of a rectangle is the length times the width.

Circle2D class

Also make this class inherit from the Shape2D class. Have it store a radius as a field. Provide a constructor that takes a double argument and uses it to set the field. Note, the area of a circle is PI times it's radius times it's radius.

Shape2DAdder class

Have this class provide a single method named sumAreas() that takes two objects, and each one can either be a Rectangle2D or a Circle2D object (and you cannot use an Object type parameter). Have the method return (not display) the sum of area of both objects.