Question 1: POJOs
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
A private access controller is only accessible within the same class, while a public access controller is accessible from any other class to be modified. In terms of POJOs, private access controllers allow for data encapsulation, protecting from any unwanted changes.
b. Identify a scenario when you would use the private vs. public access controllers that isn’t the one given in the scenario above
There could be a banking app where a person’s balance is stored within an object. You would want the balance to use private access controllers so that the balance is not modified by any other class. Other methods for depositing and withdrawing cash could be public, but the balance method itself should not be played around with, making it best for it to be a private access controller.
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
import java.util.Date;
public class Book {
// Private fields
private String title;
private String author;
private Date datePublished;
private String personHoldingBook;
// Constructor
public Book(String title, String author, Date datePublished, String personHoldingBook) {
this.title = title;
this.author = author;
this.datePublished = datePublished;
this.personHoldingBook = personHoldingBook;
}
// Getters and setters
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDatePublished() {
return datePublished;
}
public void setDatePublished(Date datePublished) {
this.datePublished = datePublished;
}
public String getPersonHoldingBook() {
return personHoldingBook;
}
public void setPersonHoldingBook(String personHoldingBook) {
this.personHoldingBook = personHoldingBook;
}
// toString method
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", datePublished=" + datePublished +
", personHoldingBook='" + personHoldingBook + '\'' +
'}';
}
}
Question 2: Writing Classes
(a) Describe the different features needed to create a class and what their purpose is: A class declaration to declare a class, variables declared within a class to represent object properties, constructors to initialize objects, methods within a class to define how objects behave, access controllers to determine which fields can be modified, and getters/setters to modify values of private fields are all key components to create 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 {
// Attributes
private String accountHolder;
private double balance;
// Constructor
public BankAccount(String accountHolder, double initialBalance) {
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
public void setAccountHolder(String name) {
this.accountHolder = name;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(amount + " deposited successfully.");
} else {
System.out.println("Invalid deposit amount. Amount must be positive.");
}
}
public void withdraw(double amount) {
if (amount > 0) {
if (amount <= balance) {
balance -= amount;
System.out.println(amount + " withdrawn successfully.");
} else {
System.out.println("Insufficient funds. Withdrawal amount exceeds balance.");
}
} else {
System.out.println("Invalid withdrawal amount. Amount must be positive.");
}
}
// cant withdraw more than exists
private void ensureNonNegativeBalance() {
if (balance < 0) {
balance = 0;
}
}
// Getters
public String getAccountHolder() {
return accountHolder;
}
public double getBalance() {
return balance;
}
// testing purposes lol
public static void main(String[] args) {
// Create a bank account
BankAccount account = new BankAccount("John Doe", 1000.0);
// Display initial balance
System.out.println("Initial balance: $" + account.getBalance());
// Deposit $500
account.deposit(500.0);
// Withdraw $200
account.withdraw(200.0);
// Withdraw $2000 (exceeding balance)
account.withdraw(2000.0);
// Display final balance
System.out.println("Final balance: $" + account.getBalance());
}
}
BankAccount.main(null);
Initial balance: $1000.0
500.0 deposited successfully.
200.0 withdrawn successfully.
Insufficient funds. Withdrawal amount exceeds balance.
Final balance: $1300.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: Inheritance is a key component of object oriented programming which allows for a subclass to inherit the properties of a parent class, allowing for easy code reusability and functionality extension. An example where inheritance could be useful is where there is a parent class called “Animal”, and then creating a subclass “dog” that inherits the properties of the parent class in order to reuse that code but add ceryain functionalities for the child class in specific.
(b) 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 representing all animals
class Animal {
// private instance variables
private String name;
private int age;
// constructors
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display generic information about an animal
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// extending animal class with mammal subclass
class Mammal extends Animal {
// Additional attribute for mammals
private String furColor;
// Constructor
public Mammal(String name, int age, String furColor) {
super(name, age); // Call superclass constructor
this.furColor = furColor;
}
// Method to display specific information about mammals
public void displayMammalInfo() {
displayInfo(); // Call superclass method
System.out.println("Fur Color: " + furColor);
}
}
// Subclass representing birds
class Bird extends Animal {
// Additional attribute for birds
private boolean canFly;
// Constructor
public Bird(String name, int age, boolean canFly) {
super(name, age); // Call superclass constructor
this.canFly = canFly;
}
// Method to display specific information about birds
public void displayBirdInfo() {
displayInfo(); // Call superclass method
System.out.println("Can Fly: " + canFly);
}
}
// Subclass representing reptiles
class Reptile extends Animal {
// Additional attribute for reptiles
private boolean isColdBlooded;
// Constructor
public Reptile(String name, int age, boolean isColdBlooded) {
super(name, age); // Call superclass constructor
this.isColdBlooded = isColdBlooded;
}
// repitle information
public void displayReptileInfo() {
displayInfo(); // superclass method
System.out.println("Is Cold-Blooded: " + isColdBlooded);
}
}
// Main class for testing
public class Zoo {
public static void main(String[] args) {
// different animals
Mammal lion = new Mammal("Lion", 5, "Golden");
Bird eagle = new Bird("Eagle", 3, true);
Reptile snake = new Reptile("Snake", 2, true);
// printing info
System.out.println("Mammal Information:");
lion.displayMammalInfo();
System.out.println();
System.out.println("Bird Information:");
eagle.displayBirdInfo();
System.out.println();
System.out.println("Reptile Information:");
snake.displayReptileInfo();
}
}
Zoo.main(null);
Mammal Information:
Name: Lion
Age: 5
Fur Color: Golden
Bird Information:
Name: Eagle
Age: 3
Can Fly: true
Reptile Information:
Name: Snake
Age: 2
Is Cold-Blooded: true