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

One one hand, an attribute or method declared as public in a POJO means that it can be accessed from any other class in the application. This allows other parts of the program to interact with the public fields or methods and the internal state of the object to be modified from anywhere. On the other hand, declaring an attribute or method as private restricts access to it from outside the class in which it is declared, so only the methods within the same class can directly access and modify these fields. This ensures that the internal state of an object is protected and can only be changed through controlled methods (getters and setters).

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

If I wanted to make a system that handles sensitive information, such as a person’s banking info, I would use private access modifiers for the fields that store the user’s account number, balance, and personal details. I would choose private access controllers so that these details can’t be directly accessed or modified from outside the class, protecting the data from unauthorized access and enhancing data security.

I would really only use public access modifiers for something that does not really deal with sensitive information and is intended to be easily accessible from anywhere in the application without affecting the application’s state, such as certain mathematical constants (like pi or e) or utility conversion methods

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 {
    private String title;
    private String author;
    private String datePublished;
    private String personHolding;

    public Book(String title, String author, String datePublished) {
        this.title = title;
        this.author = author;
        this.datePublished = datePublished;
        this.personHolding = null; // Initially, no one is holding the book
    }

    // Getters
    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public String getDatePublished() {
        return datePublished;
    }

    public String getPersonHolding() {
        return personHolding;
    }

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

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

    public void setDatePublished(String datePublished) {
        this.datePublished = datePublished;
    }

    public void setPersonHolding(String personHolding) {
        this.personHolding = personHolding;
    }

    public static void main(String[] args) {
        // Creating a new Book instance
        Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", "1925");
        
        // Prints initial details
        System.out.println("Book 1 Initial Details:");
        printBookDetails(book1);
        
        // Updates the person holding the book
        book1.setPersonHolding("me");

        // Printing final details
        System.out.println("\nBook 1 Updated Details:");
        printBookDetails(book1);

    }

    private static void printBookDetails(Book book) {
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Date Published: " + book.getDatePublished());
        String personHolding = book.getPersonHolding();
        if (personHolding != null) {
            System.out.println("Person Holding: " + personHolding);
        } else {
            System.out.println("Person Holding: None");
        }
    }


}

Book.main(null);

Book 1 Initial Details:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Date Published: 1925
Person Holding: None

Book 1 Updated Details:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Date Published: 1925
Person Holding: me

Question 2 - Writing Classes:

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

  • Attributes/Fields: Variables that hold the data or state of the class instances, represent the properties of the objects created from the class.
  • Methods: Functions that define the behavior of the class, can access and modify the attributes of the class and provide functionality to the class.
  • Constructor: A special method that is called when an instance of the class is created, initialize the newly created object.
  • Access Modifiers: Keywords that determine the visibility of fields and methods (ex. private, public, and protected)
  • Encapsulation: Keeping fields private and providing public getter and setter methods to access and modify the values of these fields.

(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 {
    private String accountHolder;
    private double balance;

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

    // Setters
    public void setAccountHolder(String name) {
        this.accountHolder = name;
    }

    public void deposit(double amount) {
        if(amount > 0) {
            this.balance += amount;
        }
    }

    public void withdraw(double amount) {
        if(amount > 0 && amount <= this.balance) { // ensures the withdrawal amount is less than or equal to the current balance
            this.balance -= amount;
        }
    }

    // Getters
    public String getAccountHolder() {
        return accountHolder;
    }

    public double getBalance() {
        return balance;
    }

    public static void main(String[] args) {
        // Create new BankAccount instance
        BankAccount account1 = new BankAccount("John Doe", 1000.00);

        // Display initial balance
        System.out.println("Initial balance: $" + account1.getBalance());

        // Deposit
        account1.deposit(500.00);
        System.out.println("Balance after deposit: $" + account1.getBalance());

        // Withdraw 
        account1.withdraw(200.00);
        System.out.println("Balance after withdrawal: $" + account1.getBalance());

        // withdraws more than the balance, balance remains unchanged
        account1.withdraw(2000.00);
        System.out.println("Balance after withdrawal: $" + account1.getBalance());
    }

}
BankAccount.main(null);

Initial balance: $1000.0
Balance after deposit: $1500.0
Balance after withdrawal: $1300.0
Balance after withdrawal: $1300.0

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.

Wrapper classes in Java are used to convert primitive data types into objects. This is useful because in Java, there are cases where you need to use primitives as objects, such as in collections which cannot hold primitives. Each primitive data type has a corresponding wrapper class, e.g., int has Integer, double has Double, and so on.


Integer myInt = 5; // conversion of primitive to Integer object
int myPrimitive = myInt; // conversion of Integer object to primitive


(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.

public class Temperature {
    private double celsius;

    public Temperature(double celsius) {
        this.celsius = celsius;
    }

    public double getTemperature() {
        return celsius;
    }

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

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

    public static void main(String[] args) {
        Temperature temp = new Temperature(0); // Freezing point of water

        System.out.println("Temperature in Celsius: " + temp.getTemperature() + "°C");
        System.out.println("Temperature in Fahrenheit: " + temp.toFahrenheit() + "°F");

        temp.setTemperature(100); // Boiling point of water
        System.out.println("New Temperature in Celsius: " + temp.getTemperature() + "°C");
        System.out.println("New Temperature in Fahrenheit: " + temp.toFahrenheit() + "°F");
    }

}

Temperature.main(null);
Temperature in Celsius: 0.0°C
Temperature in Fahrenheit: 32.0°F
New Temperature in Celsius: 100.0°C
New Temperature in Fahrenheit: 212.0°F

Question 5 - Inheritence:

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.

Inheritance allows a class to inherit properties and methods from another class. The class that inherits is called a subclass, and the class from which it inherits is called a superclass.

One example scenario where inheritance is useful is in a user interface (UI) framework where different types of UI elements (buttons, checkboxes, dropdowns) share common properties (like position, size, color) and behaviors. By using inheritance, these common features can be defined in a superclass (e.g., UIElement), and each specific UI element class can inherit from it, reducing redundancy and enhancing maintainability.

(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.

// Superclass for all animals
public class Animal {
    protected String name;
    protected String diet; 
    protected String habitat; 

    public Animal(String name, String diet, String habitat) {
        this.name = name;
        this.diet = diet;
        this.habitat = habitat;
    }

    // Method to depict eating behavior
    public void eat() {
        System.out.println(name + " the " + this.getClass().getSimpleName() + " is eating " + diet + ".");
    }

    // Method to depict sleeping behavior
    public void sleep() {
        System.out.println(name + " the " + this.getClass().getSimpleName() + " is sleeping in " + habitat + ".");
    }
}

// Subclass for Birds
public class Bird extends Animal {
    private boolean canFly;

    public Bird(String name, String diet, String habitat, boolean canFly) {
        super(name, diet, habitat);
        this.canFly = canFly;
    }

    // Method specific to birds
    public void fly() {
        if (canFly) {
            System.out.println(name + " the Bird is flying.");
        } else {
            System.out.println(name + " the Bird cannot fly.");
        }
    }
}

// Subclass for Mammals
public class Mammal extends Animal {
    private boolean isAquatic;

    public Mammal(String name, String diet, String habitat, boolean isAquatic) {
        super(name, diet, habitat);
        this.isAquatic = isAquatic;
    }

    // Method specific to mammals
    public void swim() {
        if (isAquatic) {
            System.out.println(name + " the Mammal is swimming.");
        } else {
            System.out.println(name + " the Mammal cannot swim.");
        }
    }
}

// Subclass for Reptiles
public class Reptile extends Animal {
    private boolean isVenomous;

    public Reptile(String name, String diet, String habitat, boolean isVenomous) {
        super(name, diet, habitat);
        this.isVenomous = isVenomous;
    }

    // Method specific to reptiles
    public void baskInSun() {
        System.out.println(name + " the Reptile is basking in the sun.");
    }
}

public class ZooTest { // test case
    public static void main(String[] args) {
        Animal genericAnimal = new Animal("Generic Animal", "omnivore", "generic habitat");
        Bird eagle = new Bird("Eagle", "carnivore", "mountains", true);
        Mammal dolphin = new Mammal("Dolphin", "fish", "ocean", true);
        Reptile snake = new Reptile("Snake", "carnivore", "jungle", true);

        genericAnimal.eat();
        genericAnimal.sleep();

        eagle.eat();
        eagle.sleep();
        eagle.fly();

        dolphin.eat();
        dolphin.sleep();
        dolphin.swim();

        snake.eat();
        snake.sleep();
        snake.baskInSun();
    }
}

ZooTest.main(null);

Generic Animal the Animal is eating omnivore.
Generic Animal the Animal is sleeping in generic habitat.
Eagle the Bird is eating carnivore.
Eagle the Bird is sleeping in mountains.
Eagle the Bird is flying.
Dolphin the Mammal is eating fish.
Dolphin the Mammal is sleeping in ocean.
Dolphin the Mammal is swimming.
Snake the Reptile is eating carnivore.
Snake the Reptile is sleeping in jungle.
Snake the Reptile is basking in the sun.