Learn AP Comp Sci

Problem of the Day

Problem:

Consider the following method which models a door in a house.

public class Door
{
private boolean isOpen;

public Door()
{
isOpen = false;
}

public void open()
{
isOpen = true;
}

public void close()
{
isOpen = false;
}

public boolean canWalkThrough()
{
return isOpen;
}
}

A Door object is created with the instruction

Door kitchenDoor = new Door();

Which instruction(s) will open kitchenDoor?

  1. kitchenDoor.open();
  2. Door.open();
  3. kitchenDoor.isOpen = true;
  1. I only
  2. II only
  3. III only
  4. I and II only
  5. I and III only

Show solution:

The correct answer is a. Methods are defined in a class, but called on objects (instances) of the class, so option II is incorrect. And the boolean variable isOpen has private access, so we can't directly set it as option III tries to do.