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 access controller: The public access controller allows for an attribute or method to be able to accessed from other classes and methods. This for instance will allow the attributes of the POJO to be changed from different packages or from different areas of the program outside of the class for instance a person POJO with a public age attribute using person.age = 20 within the main method would allow us to change and set this value, something that we couldn’t do if the attribute was private.

  • Private access controller: The private access controller allows for an attribute or method to be able to accessed only within the parent class. This in the POJO would mean that if we tried to access the private attribute from a different area in the program would result in an error. Say for instance the person POJO from earlier that had an age attribute but now instead if it were private we when we attempted to do person.age = 20 with the main method we would get the error informing us of the private access of the variable and that we can’t access it.

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

  • Say we have a class that is a cookie and these cookies have specific attributes like the fat content, sugars, etc. We wouldn’t want these values to have a public access controls as they should not be able to be modified after the fact as it would change the cookie and its properties that wouldn’t be realistic in a retail setting. However for a price property we would want this to be public as the price of the cookie could change and we would thus want to be able to dynamically alter it as needed making it better ot have it be under a public access controller.
public class Cookie {
    private int fatContent;
    private int sugars;
    public double price;

    public Cookie(int fatContent, int sugars, double price) {
        this.fatContent = fatContent;
        this.sugars = sugars;
        this.price = price;
    }

    public int getFatContent() {
        return fatContent;
    }

    public void getSugars() {
        return sugars;
    }

    public double getPrice() {
        return price;
    }
}

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


// Person Class for storing person details and basic functionality needed for Book class
public class Person{
    private String name;
    private int age;
    private String address;
    private String phoneNumber;
    private String email;

    public Person(String name, int age, String address, String phoneNumber, String email){
        this.name = name;
        this.age = age;
        this.address = address;
        this.phoneNumber = phoneNumber;
        this.email = email;
    }

    // Writing the toString method to be able to print the object
    public String toString(){
        return "Name: " + name + "\nAge: " + age + "\nAddress: " + address + "\nPhone Number: " + phoneNumber + "\nEmail: " + email;
    }
}

public class Book{
    private String title;
    private String author;
    private Person person;
    private String publishDate;
    
    public Book(String title, String author, Person person, String publishDate){
        this.title = title;
        this.author = author;
        this.person = person;
        this.publishDate = publishDate;
    }

    // Setters and getters to be able to change and get private variables
    public String getTitle(){
        return title;
    }

    public String getAuthor(){
        return author;
    }

    public Person getPerson(){
        return person;
    }

    public String getPublishDate(){
        return publishDate;
    }

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

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

    public void setPerson(Person person){
        this.person = person;
    }

    public void setPublishDate(String publishDate){
        this.publishDate = publishDate;
    }

    public static void main(String[] args){
        Person person = new Person("Shaurya Goel", 14, "1234 Main St", "123-456-7890", "goel1@email.net");   
        Book book = new Book("Hustler's University a Compendium; Romanian Big Mike", "Andrew Tate", person, "01/01/2020");

        System.out.println("\nBefore changing the values");
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Person: " + book.getPerson());
        System.out.println("Publish Date: " + book.getPublishDate());


        book.setTitle("Hustler's University a Compendium; UK Big Mike");
        book.setAuthor("Tristan Tate");
        book.setPerson(new Person("Shvinash Goel", 14, "1234 Main St", "123-456-7890", "goel2@hotmail.net"));
        book.setPublishDate("01/01/2021");

        System.out.println("\nAfter changing the values");
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Person: " + book.getPerson());
        System.out.println("Publish Date: " + book.getPublishDate());


    }
}

Book.main(null);
Before changing the values
Title: Hustler's University a Compendium; Romanian Big Mike
Author: Andrew Tate
Person: Name: Shaurya Goel
Age: 14
Address: 1234 Main St
Phone Number: 123-456-7890
Email: goel1@email.net
Publish Date: 01/01/2020

After changing the values
Title: Hustler's University a Compendium; UK Big Mike
Author: Tristan Tate
Person: Name: Shvinash Goel
Age: 14
Address: 1234 Main St
Phone Number: 123-456-7890
Email: goel2@hotmail.net
Publish Date: 01/01/2021

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 is a special method that is used to initialize an object. When we create an object the constructor is called and what happens within the it is that the memory that is needed for the object is allocated. This happens we we the new keyword and call the constructor. The default constructor for any method is a no argument constructor that is called when we don’t specify a constructor.

(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 Cheeses{
    public String color;
    public String variety;
    public int age;

    public Cheeses(){
        this.color = "White";
        this.variety = "Cheddar";
        this.age = 0;
    }
    
    public Cheeses(String color, String variety, int age){
        this.color = color;
        this.variety = variety;
        this.age = age;
    }

    // Setters and getters to be able to change and get private variables
    public String getColor(){
        return color;
    }

    public String getVariety(){
        return variety;
    }

    public int getAge(){
        return age;
    }

    public void setColor(String color){
        this.color = color;
    }

    public void setVariety(String variety){
        this.variety = variety;
    }

    public void setAge(int age){
        this.age = age;
    }


    public String toString(){
        return "Color: " + color + "\nVariety: " + variety + "\nAge: " + age;
    }

    public static void main(String[] args){
        System.out.println("\nFunction Call with Default Constructor");
        Cheeses cheese2 = new Cheeses(); // Constructor 1
        System.out.println(cheese2);
        

        System.out.println("\nFunction Call with Overloaded Constructor");
        Cheeses cheese = new Cheeses("Yellow", "Cheddar", 5); // Constructor 2
        System.out.println(cheese);        
    }
}

Cheeses.main(null);

Function Call with Default Constructor
Color: White
Variety: Cheddar
Age: 0

Function Call with Overloaded Constructor
Color: Yellow
Variety: Cheddar
Age: 5

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 in Java is the mechanism of taking one class and creating a new class based off of the old class, that allows you to reuse methods and properties of that old class, while being able to build off of it. This is useful when we have a parent with base properties and want to have a child that has these properties and it own as well.

(b) Code:

public class Sweet{
    public int sugarContentGrams;
    public int calories;
    public String name;
}

public class Rasgulla extends Sweet{
    String material = "Paneer";
    int price;
    
    public Rasgulla(){
        this.sugarContentGrams = 20;
        this.calories = 100;
        this.name = "Rasgulla";
        this.price = 10;
    }

    public Rasgulla(int sugarContentGrams, int calories, String name){
        this.sugarContentGrams = sugarContentGrams;
        this.calories = calories;
        this.name = name;
        this.price = 10;
    }

    public String toString(){
        return "Name: " + name + "\nSugar Content: " + sugarContentGrams + "g\nCalories: " + calories + "\nMaterial: " + material + "\nPrice: " + price;
    }

    public static void main(String[] args){
        Rasgulla rasgulla = new Rasgulla(30, 150, "Moplees Rasgulla"); // Constructor 2
        System.out.println(rasgulla);        
    }
}

Rasgulla.main(null);

// Using properties of the parent class to prevent overlap
Name: Moplees Rasgulla
Sugar Content: 30g
Calories: 150
Material: Paneer
Price: 10

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 Animal representing common attributes and methods of all animals
public class Animal {
    private String name;
    private int age;
    
    // Constructor for Animal class
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Getters and setters for name and age
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    // Method to display information about the animal
    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

// Subclass representing specific type of animal - Lion
public class Lion extends Animal {
    private int numberOfTeeth;
    
    // Constructor for Lion class
    public Lion(String name, int age, int numberOfTeeth) {
        super(name, age); // Calling the constructor of superclass Animal, using inheritance we are able to layer on all the other properties we defined earlier but now can add the additional teeth property
        this.numberOfTeeth = numberOfTeeth;
    }
    
    // Getter and setter for numberOfTeeth
    public int getNumberOfTeeth() {
        return numberOfTeeth;
    }
    
    public void setNumberOfTeeth(int numberOfTeeth) { // A new method for that uses the number of teeth property, specific to the lion class
        this.numberOfTeeth = numberOfTeeth;
    }
    
    public void roar() { // A new method specific to the lion class this contains properties are not inherited from the parent class
        System.out.println("Roar!");
    }

    // Method to display information about the lion
    public void displayInfo() {
        super.displayInfo(); // Calling the displayInfo() method of superclass Animal, and adding in the additional element that we don't get from inheritance
        System.out.println("Number of Teeth: " + numberOfTeeth);
    }
}

// Subclass representing specific type of animal - Elephant
public class Elephant extends Animal {
    private int trunkLength;
    
    // Constructor for Elephant class
    public Elephant(String name, int age, int trunkLength) {
        super(name, age); // Calling the constructor of superclass Animal
        this.trunkLength = trunkLength; // Trunk a unique elephant property that we do not get from the parent class
    }
    
    // Getter and setter for trunkLength, a new property specific to the elephant class
    public int getTrunkLength() {
        return trunkLength;
    }
    
    public void setTrunkLength(int trunkLength) {
        this.trunkLength = trunkLength;
    }

    public void trumpet() { // A new method specific to the elephant class, that has a unique property that is not inherited from the parent class making it different
        System.out.println("Trumpet!");
    }
    
    // Method to display information about the elephant
    public void displayInfo() {
        super.displayInfo(); // Calling the displayInfo() method of superclass Animal
        System.out.println("Trunk Length: " + trunkLength); // Adding the trunk length property to the display and building off the inherited method
    }
}

// Subclass representing specific type of animal - Giraffe
public class Giraffe extends Animal {
    private int neckLength; // Long neck is a unique property of the giraffe class and we don't inherit this from the parent class
    
    // Constructor for Giraffe class
    public Giraffe(String name, int age, int neckLength) {
        super(name, age); // Calling the constructor of superclass Animal
        this.neckLength = neckLength;
    }
    
    // Getter and setter for neckLength
    public int getNeckLength() {
        return neckLength;
    }
    
    public void setNeckLength(int neckLength) {
        this.neckLength = neckLength;
    }

    public void neckSlapDefense() { // A new method specific to the giraffe class, that has a unique property that is not inherited from the parent class making it different 
        System.out.println("Neck Slap Defense!"); // Predator defense mechanism unique to giraffes not present in parent class and not given to other subclasses
        if (neckLength > 200) {
            System.out.println("Neck Slap Defense Successful!");
        } else {
            System.out.println("Neck Slap Defense Failed!");
        }
         
    }
    
    // Method to display information about the giraffe
    public void displayInfo() {
        super.displayInfo(); // Calling the displayInfo() method of superclass Animal
        System.out.println("Neck Length: " + neckLength); // Adding the neck length property to the display and building off the inherited method
    }
}

// Testing of the various classes

public class TestAnimal {
    public static void main(String[] args) {
        // Create a Lion object
        Lion lion = new Lion("Simba", 5, 30);
        lion.displayInfo(); // Display lion's information
        lion.roar(); // Lion roars
        System.out.println("Number of Teeth: " + lion.getNumberOfTeeth()); // Get the number of teeth
        
        // Create an Elephant object
        Elephant elephant = new Elephant("Dumbo", 10, 200);
        elephant.displayInfo(); // Display elephant's information
        elephant.trumpet(); // Elephant trumpets
        System.out.println("Trunk Length: " + elephant.getTrunkLength()); // Get the trunk length
        
        // Create a Giraffe object
        Giraffe giraffe = new Giraffe("Melman", 7, 250);
        giraffe.displayInfo(); // Display giraffe's information
        giraffe.neckSlapDefense(); // Giraffe performs neck slap defense
        System.out.println("Neck Length: " + giraffe.getNeckLength()); // Get the neck length
    }
}

TestAnimal.main(null);




Name: Simba
Age: 5
Number of Teeth: 30
Roar!
Number of Teeth: 30
Name: Dumbo
Age: 10
Trunk Length: 200
Trumpet!
Trunk Length: 200
Name: Melman
Age: 7
Neck Length: 250
Neck Slap Defense!
Neck Slap Defense Successful!
Neck Length: 250