Code duplication is undesirable!
- Recognize inheritance can provide code reuse.
Here is the Student class from the previous chapter:
Student class
public class Student {
private String name;
private String email;
public Student(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
Let's define a new class GradStudent:
public class GradStudent {
private String name;
private String email;
private String advisor;
public GradStudent(String name, String email) {
this.name = name;
this.email = email;
}
public void setAdvisor(String advisor) {
this.advisor = advisor;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getAdvisor() {
return advisor;
}
}
Exercise what are the similarities and differences between the GradStudent and Student classes?
Solution
- Both have
nameandemailattributes with corresponding getter methods. - The
GradStudentalso has anadvisorattribute with corresponding setter and getter methods.
Notice there is considerable overlap (code duplication) between Student and GradStudent classes (which is expected since a grad student is a [specific kind of] student).
Duplicate code is generally considered undesirable.
How can we reuse code from Student class in GradStudent? One of the ways we can achieve code reuse is through the inheritance mechanism in object-oriented programming. We will explore inheritance in detail in this chapter.
Resources
- Wikipedia entry on duplicate code.
- Refactoring Guru article on duplicate code