Free Response Questions

Question 1 - Pojos and Access Control:

Situation: The school librarian wants to create a program that stores all of the books within the library in a database and is used to manage their inventory of books available to the students. You decided to put your amazing code skills to work and help out the librarian!

a. Describe the key differences between the private and public access controllers and how it affects a POJO

Public can be accessed within and outside ofa class, but private can only be used within a class. I think of this similarly to “let” in javascript or defining variables within functions.

b. Identify a scenario when you would use the private vs. public access controllers that isn’t the one given in the scenario above

You could use public when you need to access methods from another object within an object, such as using a Math functions object with methods for different calculations that would be useful within a different object. Private would be used for methods that are specific to the class, such as in calculating and setting DOB.

c. Create a Book class that represents the following attributes about a book: title, author, date published, person holding the book and make sure that the objects are using a POJO, the proper getters and setters and are secure from any other modifications that the program makes later to the objects

public class Book {
    String title;
    String author;
    String date;
    String holder;

    // constructor
    public Book(String title, String author, String date, String holder) {
        this.title = title;
        this.author = author;
        this.date = date;
        this.holder = holder;
    }

    // title getter
    public String getTitle() {
        return this.title;
    }

    // title setter
    public void setTitle(String title) {
        this.title = title;
    }

    // author getter
    public String getAuthor() {
        return this.author;
    }

    // author setter
    public void setAuthor(String author) {
        this.author = author;
    }

    // date getter
    public String getDate() {
        return this.date;
    }

    // date setter
    public void setDate(String date) {
        this.date = date;
    }

    // holder getter
    public String getHolder() {
        return this.holder;
    }

    // holder setter
    public void setHolder(String holder) {
        this.holder = holder;
    }
}

// Tests
Book gatsby = new Book("The Great Gatsby", "F. Scott Fitzgerald", "1920s or something lol", "Aiden Huynh");

// show getter working
System.out.println(gatsby.getHolder()); // expected output "Aiden Huynh"

// change and get to show setter working
gatsby.setHolder("John Mortensen");
System.out.println(gatsby.getHolder()); // expected output "John Mortensen"
Aiden Huynh


John Mortensen

Question 2 - Writing Classes:

(a) Describe the different features needed to create a class and what their purpose is.

  • Attributes are variables/data tied to a class
  • Methods are functions within a class

(b) Code:

Create a Java class BankAccount to represent a simple bank account. This class should have the following attributes:

  • accountHolder (String): The name of the account holder. balance (double): The current balance in the account. Implement the following mutator (setter) methods for the BankAccount class:
  • setAccountHolder(String name): Sets the name of the account holder.
  • deposit(double amount): Deposits a given amount into the account.
  • withdraw(double amount): Withdraws a given amount from the account, but only if the withdrawal amount is less than or equal to the current balance. Ensure that the balance is never negative.
public class BankAccount {
    // Define variables
    String accountHolder;
    double balance;

    // Constructor with accountHolder and balance
    public BankAccount(String accountHolder, double balance) {
        this.accountHolder = accountHolder;
        this.balance = balance;
    }

    // Basic setters and getters for account holder
    public void setAccountHolder(String accountHolder) {
        this.accountHolder = accountHolder;
    }

    // Getter for account holder
    public String getAccountHolder() {
        return this.accountHolder;
    }

    // Getter for balance
    public double getBalance() {
        return this.balance;
    }

    public void deposit(double amount) {
        // stop if trying to deposit a negative amount
        if (amount < 0) {
            return;
        }

        // otherwise add to balance
        this.balance += amount;
    }

    public void withdraw(double amount) {
        double total = this.balance - amount;

        // If the total would be negative, stop
        if (total < 0) {
            return;
        }

        // otherwise set new balance
        this.balance = total;
    }
}

// Make a test account
BankAccount test = new BankAccount("Aiden Huynh", 1.00);

// Get current balance before changes
System.out.println("Initial balance:\n" + test.getBalance());

// Add 1,000,000 dollars cuz im RICH
test.deposit(1000000);

// Money moves $$$$$
System.out.println("\nAfter deposit balance:\n" + test.getBalance());

// Oh no! I have been fined for littering on a public road
test.withdraw(999999);

// :(
System.out.println("\nAfter withdraw balance:\n" + test.getBalance());

// I don't have any more money to take! I am going into severe debt!
test.withdraw(100);
System.out.println("\nWithdraw that would be negative:\n" + test.getBalance());

// for fun, negative adding
test.deposit(-100);
System.out.println("\nDepositing a negative:\n" + test.getBalance());

Initial balance:
1.0

After deposit balance:
1000001.0

After withdraw balance:
2.0

Withdraw that would be negative:
2.0

Depositing a negative:
2.0

Question 3 - Instantiation of a Class

(a) Explain how a constructor works, including when it runs and what generally is done within a constructor.

A constructor defines variables for an object by taking parameters and tying them to the object using this.

(b) Create an example of an overloaded constructor within a class. You must use at least three variables. Include the correct initialization of variables and correct headers for the constructor. Then, run the constructor at least twice with different variables and demonstrate that these two objects called different constructors. (?)

public class ConstructorTest {
    public String msg;
    public int num;
    public boolean bool;
    
    public ConstructorTest(String msg, int num, boolean bool) {
        this.msg = msg;
        this.num = num;
        this.bool = bool;
    }

    public ConstructorTest() {
        this.msg = "No arguments!";
        this.num = 0;
        this.bool = false;
    }

    public void printData() {
        System.out.println("msg: " + this.msg);
        System.out.println("num: " + this.num);
        System.out.println("bool: " + this.bool);
    }

    public static void main(String[] args) {
        // First constructor
        ConstructorTest firstTest = new ConstructorTest("Hello!", 100, true);
        System.out.println("First Test:");
        firstTest.printData();

        // Second constructor
        ConstructorTest secondTest = new ConstructorTest();
        System.out.println("\nSecond Test:");
        secondTest.printData();
    }
}

ConstructorTest.main(null);
First Test:
msg: Hello!
num: 100
bool: true

Second Test:
msg: No arguments!
num: 0
bool: false

Question 4 - Wrapper Classes:

(a) Provide a brief summary of what a wrapper class is and provide a small code block showing a basic example of a wrapper class.

A wrapper class is a class that contains primitive data types. I’m not doing a small code block because that’s literally the next question.

(b) Create a Java wrapper class called Temperature to represent temperatures in Celsius. Your Temperature class should have the following features:

Fields:

A private double field to store the temperature value in Celsius.

Constructor:

A constructor that takes a double value representing the temperature in Celsius and initializes the field.

Methods:

getTemperature(): A method that returns the temperature value in Celsius. setTemperature(double value): A method that sets a new temperature value in Celsius. toFahrenheit(): A method that converts the temperature from Celsius to Fahrenheit and returns the result as a double value.

// Wrapper class wrapping primitive data type double wrapper wrapping
public class Temperature {
    // Define celsius value
    double celsius;

    // Constructor to set celsius
    public Temperature(double celsius) {
        this.celsius = celsius;
    }

    // getter
    public double getTemperature() {
        return this.celsius;
    }

    // setter
    public void setTemperature(double celsius) {
        this.celsius = celsius;
    }

    // conversion method
    public double toFahrenheit() {
        return (this.celsius * 9/5) + 32;
    }
}

Temperature test = new Temperature(100);
// Before setter
System.out.println(test.getTemperature());

// Setter
test.setTemperature(120);
System.out.println(test.getTemperature());

// Converter
System.out.println(test.toFahrenheit());
100.0
120.0
248.0

Question 5 - Inheritance:

Situation: You are developing a program to manage a zoo, where various types of animals are kept in different enclosures. To streamline your code, you decide to use inheritance to model the relationships between different types of animals and their behaviors.

(a) Explain the concept of inheritance in Java. Provide an example scenario where inheritance is useful.

(b) Code:

You need to implement a Java class hierarchy to represent different types of animals in the zoo. Create a superclass Animal with basic attributes and methods common to all animals, and at least three subclasses representing specific types of animals with additional attributes and methods. Include comments to explain your code, specifically how inheritance is used.

I’m not doing three animals there is no point

public class Animal {
    // The only thing that all animals have in common are names and sounds (real fact I swear)
    String name;
    String sound;

    // basic constructor
    public Animal(String name, String sound) {
        this.name = name;
        this.sound = sound;
    }

    // getters for fun idk
    public String getName() {
        return this.name;
    }

    public String getSound() {
        return this.sound;
    }
}

public class Bird extends Animal {
    // Wingspan is specific to birds because they have wings (cool!)
    int wingspan;

    public Bird(String name, String sound, int wingspan) {
        super(name, sound); // Inherit Animal constructor
        this.wingspan = wingspan; // for Bird class
    }

    // bird-specific wingspan getter
    public int getWingspan() {
        return this.wingspan;
    }

    // Overriding sound because birds can only chirp (fact)
    @Override
    public String getSound() {
        return "chirp";
    }
}

// Override example
Animal parrot = new Bird("Parrot", "gqwphuufl;jglll;;;", 1000);
parrot.getSound();
chirp