Week 2

Inheritance

Interfaces

Polymorphism

Error Handling in Java

Practice

Assignment

Back end Track

Content

Practice Exercises

Each section maps to a module. Exercises progress in difficulty across the week — Module 1 builds the foundation, and by Module 4 you are combining inheritance, interfaces, polymorphism, and exception handling in realistic scenarios.


Module 1 — Inheritance

Exercise 1.1 — Concept: Is-a or Has-a?

For each pair, identify the relationship as "is-a" (use inheritance) or "has-a" (use composition). Justify each in one sentence.

  1. ElectricScooter and Vehicle
  2. Player and Inventory
  3. SavingsAccount and BankAccount
  4. Invoice and Address
  5. AdminUser and User
  6. Podcast and AudioFile

Exercise 1.2 — Concept: What is Inherited?

Given the following class:

public class Person {
    private String   name;
    protected int    age;
    public String    country;

    public Person(String name, int age, String country) {
        this.name    = name;
        this.age     = age;
        this.country = country;
    }

    private void logCreation()    { System.out.println("Person created"); }
    protected void greet()        { System.out.println("Hi from Person"); }
    public String getName()       { return name; }
}

Answer without running any code:

  1. Which fields are directly accessible inside a subclass?
  2. Which methods can a subclass call using super?
  3. Can a subclass inherit and call logCreation()? Why?
  4. If a subclass calls super() with no arguments, what happens and why?

Exercise 1.3 — Bug Fixing: Broken Inheritance Chain

The following code has four mistakes. Identify each, explain why it fails, and write the corrected version.

public class Animal {
    private String name;
    private String species;

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

    public String getName() { return name; }
}

public class Dog extends Animal {
    private String breed;

    public Dog(String name, String breed) {
        this.name  = name;    // bug 1
        this.breed = breed;
    }

    @Override
    public String makeSound() {   // bug 2
        return "Woof!";
    }

    public void displayInfo() {
        System.out.println(name + " - " + breed);  // bug 3
    }
}

public class GoldenRetriever extends Dog, Animal {  // bug 4
    public GoldenRetriever(String name) {
        super(name, "Golden Retriever");
    }
}

Exercise 1.4 — Coding: Employee Hierarchy

Create the following hierarchy in com.company.model:

Employee (superclass)

Manager extends Employee

Intern extends Employee

In Main, create one of each, print them, and print each one's monthly pay.


Exercise 1.5 — Coding: toString and equals from Object

Create a Book class with fields isbn (String), title (String), author (String), year (int).

  1. Override toString() — readable single-line output
  2. Override equals() — two books are equal if their isbn is the same
  3. In Main, demonstrate:
  4. Explain in a comment: why is == not sufficient for comparing objects?

Module 2 — Interfaces

Exercise 2.1 — Concept: Interface Rules

Answer the following without writing a full program:

  1. Can an interface have a constructor? Why or why not?
  2. What is the difference between a default method and a regular interface method?
  3. A class implements two interfaces that both have a default void reset(). What must the class do?
  4. Can you instantiate an interface directly with new? What happens if you try?
  5. An interface field is declared as int MAX = 100. What are its implicit modifiers?

Exercise 2.2 — Bug Fixing: Interface Mistakes

The following code has five mistakes. Find each one, explain why it's wrong, and fix it.

public interface Discountable {
    private double DISCOUNT_RATE = 0.10;

    double applyDiscount(double price) {
        return price - (price * DISCOUNT_RATE);
    }

    double getOriginalPrice();
}

public class Product extends Discountable {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name  = name;
        this.price = price;
    }

    public double getOriginalPrice() {
        return price;
    }
}

public class Main {
    public static void main(String[] args) {
        Discountable d = new Discountable();
        System.out.println(d.applyDiscount(100.0));
    }
}

Exercise 2.3 — Coding: Delivery System

Define the following interfaces in com.delivery:

Trackable    → String getTrackingId(); String getCurrentStatus()
Insurable    → double calculateInsurance(); boolean isCovered()
Fragile      → String getHandlingInstructions(); int getMaxStackHeight()

Create three delivery item classes:

Class Implements Extra fields
StandardParcel Trackable trackingId, status
ValuableItem Trackable, Insurable trackingId, status, value
GlasswareShipment Trackable, Insurable, Fragile all of the above + maxStack

Add a static method to Trackable:

static void printAllStatuses(Trackable[] items)

that prints each item's tracking ID and current status.

Add a default method to Insurable: