Question 2 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 in Java is a mechanism where a new class (subclass) is derived from an existing class (superclass). The subclass inherits attributes and methods from its superclass, allowing for code reuse and the establishment of an “is-a” relationship between classes. This means that a subclass is a more specialized version of its superclass.

(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 representing common attributes and behaviors of all animals
class Animal {
    private String name;
    private int age;
    private String sound;

    // Constructor
    public Animal(String name, int age, String sound) {
        this.name = name;
        this.age = age;
        this.sound = sound;
    }

    // Method to make the animal make a sound
    public void makeSound() {
        System.out.println(name + " says: " + sound);
    }

    // Getter methods
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

// Subclass representing specific type of animal: Mammal
class Mammal extends Animal {
    private String furColor;

    // Constructor
    public Mammal(String name, int age, String sound, String furColor) {
        super(name, age, sound);
        this.furColor = furColor;
    }

    // Method specific to mammals
    public void giveBirth() {
        System.out.println(getName() + " gives birth to live young.");
    }
}

// Subclass representing specific type of animal: Bird
class Bird extends Animal {
    private double wingspan;

    // Constructor
    public Bird(String name, int age, String sound, double wingspan) {
        super(name, age, sound);
        this.wingspan = wingspan;
    }

    // Method specific to birds
    public void fly() {
        System.out.println(getName() + " flies with a wingspan of " + wingspan + " meters.");
    }
}

// Subclass representing specific type of animal: Reptile
class Reptile extends Animal {
    private boolean isColdBlooded;

    // Constructor
    public Reptile(String name, int age, String sound, boolean isColdBlooded) {
        super(name, age, sound);
        this.isColdBlooded = isColdBlooded;
    }

    // Method specific to reptiles
    public void sunbathe() {
        if (isColdBlooded)
            System.out.println(getName() + " sunbathes to regulate its body temperature.");
        else
            System.out.println(getName() + " does not sunbathe as it is not cold-blooded.");
    }
}

// Main class to test the implementation
public class ZooManagement {
    public static void main(String[] args) {
        // Creating instances of subclasses
        Mammal lion = new Mammal("Lion", 5, "Roar", "Golden");
        Bird eagle = new Bird("Eagle", 3, "Screech", 2.5);
        Reptile snake = new Reptile("Snake", 2, "Hiss", true);

        // Testing methods inherited from superclass
        lion.makeSound();
        eagle.makeSound();
        snake.makeSound();

        // Testing methods specific to subclasses
        lion.giveBirth();
        eagle.fly();
        snake.sunbathe();
    }
}

ZooManagement zoo = new ZooManagement();
ZooManagement.main(null);

Lion says: Roar
Eagle says: Screech
Snake says: Hiss
Lion gives birth to live young.
Eagle flies with a wingspan of 2.5 meters.
Snake sunbathes to regulate its body temperature.

Subclasses Mammal, Bird, and Reptile inherit from Animal and add specific attributes and methods relevant to their types.

Question 3: 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 in Java is a class that encapsulates, or wraps, a primitive data type within an object. This allows primitive data types to be used as objects in Java. Wrapper classes provide utility methods and help in converting primitive data types to objects and vice versa.

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

    // Constructor to initialize temperature in Celsius
    public Temperature(double celsius) {
        this.celsius = celsius;
    }

    // Getter method to get temperature in Celsius
    public double getTemperature() {
        return celsius;
    }

    // Setter method to set temperature in Celsius
    public void setTemperature(double value) {
        this.celsius = value;
    }

    // Method to convert temperature from Celsius to Fahrenheit
    public double toFahrenheit() {
        return (celsius * 9 / 5) + 32;
    }

    // Main method to test the Temperature class
    public static void main(String[] args) {
        Temperature temp = new Temperature(25.0);
        System.out.println("Temperature in Celsius: " + temp.getTemperature());
        System.out.println("Temperature in Fahrenheit: " + temp.toFahrenheit());
    }
}

Temperature temp = new Temperature(30.0);

temp.main(null)
Temperature in Celsius: 25.0
Temperature in Fahrenheit: 77.0

Question 4: Writing classes

A.

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

  • Classes require a constructor to take input data, as well as methods to execute code an access modifiers like private/public/protected

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

    // Method to set the name of the account holder
    public void setAccountHolder(String name) {
        this.accountHolder = name;
    }

    // Method to deposit a given amount into the account
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println(amount + " deposited successfully.");
        } else {
            System.out.println("Invalid amount for deposit.");
        }
    }

    // Method to withdraw a given amount from the account
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println(amount + " withdrawn successfully.");
        } else {
            System.out.println("Invalid amount for withdrawal.");
        }
    }

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

    // Main method to test the BankAccount class
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.setAccountHolder("John Doe");
        System.out.println("Account holder: " + account.accountHolder);
        account.deposit(1000);
        System.out.println("Current balance: " + account.getBalance());
        account.withdraw(500);
        System.out.println("Current balance: " + account.getBalance());
    }
}

BankAccount bank = new BankAccount();
bank.main(null);
Account holder: John Doe
1000.0 deposited successfully.
Current balance: 1000.0
500.0 withdrawn successfully.
Current balance: 500.0