2. Hierarchies
• Starting with a non-programming example, let’s consider
employees at a company:
Employee
20-page manual
Lawyer
Secretary
Marketer
5-page manual
2-page manual
2-page manual
LegalSecretary
3-page manual
2
Sunday, October 20, 13
3. Teacher class
public class Teacher {
public int getSickDays() {
return 15;
}
public String getGreeting() {
return "Welcome to class!";
}
}
• Think of this as a generic Teacher. There are some behaviors
here that might be applied to multiple teachers.
3
Sunday, October 20, 13
4. CSTeacher class
public class CSTeacher { // bad, lots of duplicate code
public int getSickDays() {
return 15;
}
public String getGreeting() {
return "Welcome to class!";
}
public String answerQuestion(String question) {
return "Hmm, " + question + " What do you think?";
}
}
• Lots of code duplication, even though we only want one new
behavior.
4
Sunday, October 20, 13
5. CSTeacher class
public class CSTeacher extends Teacher {
// extends Teacher, a CSTeacher "is a" Teacher
public String answerQuestion(String question) {
return "Hmm, " + question + " What do you think?";
}
}
• Eliminates code duplication here! We use inheritance to extend
the functionality of the base class of Teacher.
• Here, the CSTeacher is the subclass; the Teacher is the
superclass.
5
Sunday, October 20, 13