Practice Problems:   Working with Interfaces
1 Setting up Classes with Interfaces
2 Understanding Interfaces
3 Solutions

Practice Problems: Working with Interfaces

1 Setting up Classes with Interfaces

2 Understanding Interfaces

Here’s a basic setup of classes and an interface for vehicles. Use this to answer the following question about interfaces.

  interface IVehicle {

    // indicate how much a basic tune-up costs

    public double tuneUpCost();

  

    // determine whether vehicle can hold given num of passengers

    public boolean canCarry(int numPassengers);

  }

  

  class Car implements IVehicle {

    int mileage;

    int year;

    int numDoors;

  

    // constructor goes here

  

    // indicate whether car was built before given year

    boolean builtBefore(int otherYear) {

      return this.year < otherYear;

    }

  }

  

  class Bicycle implements IVehicle {

    int mileage;

    int numGears;

  

    // constructor goes here

  }

  1. What methods do you need to add to each of Car and Bicycle to get this code fragment to compile (setting aside the missing constructors)?

  2. Does having a class implement an interface change how you write its constructor?

  3. Should builtBefore be added to the IVehicle interface? Why or why not?

  4. In the Examples class, you want to define a Bicycle as follows:

      ___________ newKidsBike = new Bicycle(0, 1);

    Which types can you use in the blank line (without causing a compile error just with this single line)?

  5. Assume you defined a Car object as follows:

      IVehicle oldCar = new Car(200000, 1995, 2);

    Which methods can you call on oldCar, given the type that you gave it?

  6. Assume you defined a Car object as follows:

      Car oldCar = new Car(200000, 1995, 2);

    Which methods can you call on oldCar, given the type that you gave it?

3 Solutions

Here are the solutions.