logo

APSU Notes


Inheritance

Savitch 8.1-8.2

Topics

8.1 – Inheritance Basics

Inheritance Basics

  • It is common for a class to have instance variables and methods in common with another class.
  • Instead of writing the same code in two different classes, both classes can inherit the code from a more general class.
  • Inheritance allows a programmer to define a general class along with specialized classes that inherit the features of the general class and add additional features.
  • Example: a specialized class representing a student can inherit from a general class representing a person.

The Person Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Person {
  private String name;

  public Person() {
    name = "No name yet";
  }

  public Person(String initialName) {
    name = initialName;
  }

  public void setName(String newName) {
    name = newName;
  }

  public String getName() {
    return name;
  }

  public void writeOutput() {
    System.out.println("Name: " + name);
  }

  public boolean hasSameName(Person otherPerson) {
    return name.equalsIgnoreCase(otherPerson.name);
  }
}

Derived Classes

  • A class that inherits from another class is called a derived class or a subclass.
  • The class it inherits from is called a base class or superclass.
  • The derived class extends the base class.
  • To define a derived class in Java, use the extends keyword.
1
public class Students extends Person
  • The Student class inherits the public methods from the Person class, but not the private instance

The Student Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Student extends Person {
  private int studentNumber;

  public Student() {
    super();
    studentNumber = 0;
  }

  public Student(String initialName, int initialStudentNumber) {
    super(initialName);
    studentNumber = initialNumber;
  }

  public void reset(String newName, int newStudentNumber) {
    setName(newName);
    studentNumber = newStudentNumber;
  }

  public int getStudentNumber() {
   return studentNumber;
  }

  public void setStudentNumber(int newStudentNumber) {
    studentNumber = newStudentNumber;
  }

  public void writeOutput() {
    System.out.println("Name: " + getName());
    System.out.println("Student Number: " + studentNumber);
  }

  public boolean equals(Student otherStudent) {
    return this.hasSameName(otherStudent) &&
           (this.studentNumber == otherStudent.studentNumber);
  }
}

Objects of a Derived Class

  • Methods from both the Person class and the Student class can be called on an object of the Student class.
1
2
3
4
5
6
7
8
9
10
11
public class Inheritance Demo {

  public static void main(String[] args) {
    Student student = new Student();

    student.setName("Warren Peace"); // Person method
    student.setStudentNumber(1234);  // Student method
    student.writeOutput();           // ???
  }

}

Overriding Method Definitions

  • The Person class and the Student class both have methods called writeOutput that have no parameters.
  • The definition of writeOutput in the derived class Student overrides the definition in the base class Person.
  • When writeOutput is called on a Student object it will use the definition in the Student class.
  • The overriding method must have the same heading as the method it overrides.
  • Overriding is different from overloading, which involves multiple methods with the same name in the same class.
  • To prevent a method from being overridden, it can be declared as final.
1
public final void specialMethod();

Private Members of a Base Class

  • Private instance variables in a base class can not be accessed directly by a derived class.
1
2
3
4
public void reset(String newName, int newStudentNumber) {
  name = newName; // ILLEGAL!
  studentNumber = newStudentNumber;
}
  • Private methods of a base class can not be called directly by a derived class.
  • Private instance variables and private methods can be accessed indirectly using public methods of the base class.

UML Inheritance Diagrams

umlinheritancediagrams

8.2 – Programming with Inheritance

Constructors in Derived Classes

  • Base class constructors are not inherited by derived classes.
  • A derived class constructor can invoke a base class constructor using the keyword super.
1
2
3
4
public Student(String initialName, int initialStudentNumber) {
  super(initialName); // calls Person(String initialName)
  studentNumber = initialNumber;
}
  • The call to super must be the first statement in the constructor.
  • If there is no explicit call to a base class constructor, the default base class constructor will be called automatically.

The this Method – Again

  • The keyword this can be used to call a constructor in the same class.
1
2
3
4
5
6
7
public Person(String initialName) {
  name = initialName;
}

public Person() {
  this("No Name Yet"); // calls Person(String initialName)
}
  • Like super, a call to this must be the first statement in the constructor.
  • A constructor may not call both super and this

Calling an Overridden Method

  • The super keyword can also be used to call a base class method that has been overridden in the derived.
1
2
3
4
5
6
7
8
9
10
// Person class version
public void writeOutput() {
    System.out.println("Name: " + name);
}

// Student class version calls Person class version
public void writeOutput() {
  super.writeOutput();
  System.out.println("Student Number: " + studentNumber);
}

A Derived Class of a Derived Class

  • A derived class can extend a derived class.
1
public class Undergraduate extends Student
  • The Undergraduate class inherits the public methods of Student along with the public methods that Student inherited from Person.
1
2
3
4
Undergraduate undergrad = new Undergraduate();
undergrad.setName("Anna Karenina"); // Person method
undergrad.setStudentNumber("1878"); // Student method
undergrad.setLevel(2); // Undergraduate method

The Undergraduate Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class Undergraduate extends Student {
  private int level; // 1 for freshman, 2 for sophomore
                     // 3 for junior, or 4 for senior
  public Undergraduate() {
    super();
    level = 1;
  }

  public Undergraduate(String initialName, int initialStudentNumber,
                       int initialLevel) {
    super(initialName, initialStudentNumber);
    setLevel(intialLevel); // checks 1 <= initialLevel <= 4
  }

  public getLevel() {
    return level;
  }

  public setLevel(int newLevel) {
    if ((1 <= newLevel) && (newLevel <= 4))
      level = newLevel
    else {
      System.out.println("Illegal level!");
      System.exit(0);
    }
  }

  public void reset(String newName, int newStudentNumber, int newLevel) {
    reset(newName, newStudentNumber);
    setLevel(newLevel); // Checks 1 <= newLevel <= 4;
  }

  public void writeOutput()
  {
    super.writeOutput();
    System.out.println("StudentLevel: " + level);
  }

  public boolean equals(Undergraduate otherUG) {
    return equals((Student)otherUG) && (this.level == otherUG.level);
  }
}

Another Way to Define the equals method

  • The equals method in the Undergraduate class uses a cast to make sure it calls the Students version of equals, rather than itself.
1
2
3
4
public boolean equals(Undergraduate otherUG) {
  return equals((Student)otherUG) &&
         (this.level == otherUG.level);
}
  • Alternatively the Student version of equals could be called by using the super keyword.
1
2
3
4
public boolean equals(Undergraduate otherUG) {
  return super.equals(otherUG) &&
         (this.level == otherUG.level);
}

Type Compatibility – Method Parameters

  • An object can be passed as an argument to a method with a parameter of any class it derives from.
1
2
3
4
5
6
7
8
9
Person person = new Person("Lita Ford");
Student student = new Student("Joan Jett", "1234");
Undergraduate undergrad = new Undergraduate("Cherie Currie", "5678", 3);

if(person.hasSameName(student))  // A Student is a Person
  System.out.println("Same Name!");

if(undergrad.hasSameName(person)) // An Undergrad is a Person
  System.out.println("Same Name!");

Type Compatibility – Assignment Statements

  • An object can be assigned to a variable of any class it derives from.
1
2
3
Person p1 = new Student(); // valid
Person p2 = new Undergraduate(); // valid
Student s1 = new Undergraduate(); // valid
  • An object can not be assigned to a variable of a class than derives from it.
1
2
3
Student s = new Person(); // ILLEGAL!
Undergraduate ug1 = new Person(); // ILLEGAL!
Undergraduate ug2 = new Student(); // ILLEGAL!

The Class Object

  • Any class that doesn’t extend another class automatically extends the Object class, the ancestor of all Java classes.
  • The Objectclass contains methods that are inherited or overridden by all other classes.
1
2
public String toString()
public boolean equals(Object otherObject)
  • If a class overrides the toString method, an object of that class can be passed to the System.out.println()method:
1
2
3
Person funkyPerson = new Person("Bootsy Collins");
System.out.println(funkyPerson); // calls toString method of Person class
System.out.println(funkyPerson.toString()); // same as above

Overriding the equals Method

  • To override the equals method of the Object class, the parameter must also be of class Object.
1
2
3
4
5
public boolean equals(Object otherObject) {
  Student otherStudent = (Student)otherObject; // cast to Student
  return this.hasSameName(otherStudent) &&
         this.studentNumber == otherStudent.studentNumber;
}
  • This works in most cases, but generates a runtime error if the object is null or its class is not derived from Student.

A Better equals Method

  • The instanceof keyword determines if an object is an instance of particular class.
1
2
3
4
5
6
7
8
9
10
11
public boolean equals(Object otherObject)
{
  boolean isEqual = false;
  if ((otherObject != null) &&
      (otherObject instanceof Student)) {
    Student otherStudent = (Student)otherObject;
    isEqual = this.sameName(otherStudent) &&
              (this.studentNumber == otherStudent.studentNumber);
  }
  return isEqual;
}

Powerpoint

Quiz

Quiz 3