In addition, there is a protocol for this. The pilot will contact the flight attendant working in the front of the plane. The flight attendant will lock a beverage cart in front of the bathrooms, creating a (heavy, but not immovable) barrier between the cockpit and bathroom, and the rest of the plane. The flight attendant stands behind the cart, watching the passengers. The pilot looks through the peep hole, and when it is clear, comes out, locking the cockpit door behind him/herself. After using the rest room, the pilot knocks on the door to ask the copilot to open it. The peep hold is used to be sure the flight attendant is still standing guard and everything is normal.
There are obviously some risks here, as the door is opened briefly twice, but there are a number of steps taken to minimize this risk.