Back to our class scheduling example. Let's schedule students with other hobbies in classes too.
The requirements are updated to say:
If the student's hobby is football, then sign them up for football.
Otherwise, if the student's hobby is dance, then sign them up for dance.
Otherwise, If the student's hobby is art, then sign them up for art.
We know based on the class definition for Student, that each object can only have one hobby attribute:
public class Student { public String name; public String hobby; }
That's why the Otherwise
is such an important part of the requirements. We can represent this type of mutual exclusivity with the if-else-if
conditional. Here's a super conceptual view of an if-else-if
conditional:
if(firstCondition){ // do some thing } else if (secondCondition){ // do something else }
Here if firstCondition
is true then its code block will run and the else if
condition won't even be evaluated. It's skipped entirely.
If firstCondition
was false, then the else if
condition would be evaluated. As you can see, it's a great way to group and chain related conditionals that are mutually exclusive.
So let's apply this concept to signupBasedOnHobby
:
public class StudentScheduleController { public void signupBasedOnHobby(Student s){ if(s.hobby == 'football'){ footballSignup(s); // Only call this line if the student's hobby is football } else if (s.hobby == 'dance'){ danceSignup(s); } else if (s.hobby == 'art'){ artSignup(s); } } }
Let's go! So now, if a student's hobby is football
the first conditional will evaluate to true, and the second and third ones will be skipped. If their hobby is art
, the first conditional will evaluate to false, it'll then evaluate the second as true and execute it's body. The third conditional won't be evaluated at all and will be skipped.