Welcome to Lesson 11!

Learning Objectives
By the end of today's class, you should know...
  • What is inheritance
  • What is the difference between a super class and a subclass
  • How do you override inherited methods
  • What is the difference between overriding and overloading
  • How do you write constructors for subclasses
  • How do you use the keyword super to call methods from the super class
  • The differences among public, private, protected, and package access


1. Introducing Inheritance

Inheritance: the ability to define new classes from existing ones.

  • Inheritance is one of the important ideas of object-oriented programming
  • It lets you write a class that is based on another class
  • When used correctly, inheritance can simplify the overall design
  • As you will discover, Java uses inheritance extensively in its API

How Inheritance Works

  • A class that is inherited from is called the superclass (a.k.a. base, parent)
  • A class that inherits is called the subclass (a.k.a. derived, child)
  • The subclass automatically contains all the variable and method definitions of the superclass
  • In a subclass, you can define new member variables and methods not found in the superclass
  • The two classes in the following diagram show how this works
An inheritance diagram where checking account and savings account classes inherit from bank account

  • Here the superclass is a BankAccount
  • The class has several variables and methods used to define a BankAccount object
  • For instance, getBalance() returns the current totalBalance
  • In the CheckingAccount and SavingAccount subclasses you can use all the variables and methods inherited from BankAccount
  • In addition, you can add new fields, constants and methods

About the Diagram

  • The first rectangular section of a class diagram contains the class name
  • The second section describes the attributes (fields or variables)
  • The third (bottom) section describes the operations (methods)
  • A minus sign (-) marks attributes and operations are private, i.e. that cannot be accessed by other classes, including child classes (private)
  • A plus sign (+) marks attributes and operations that are public, i.e. that can be accessed by other classes
  • Parameters are listed in parenthesis separated by commas
  • The upward pointing arrow indicates inheritance

Class Hierarchies

  • You can derive classes from derived classes
    • Subclasses become superclasses for their descendants
    • Child classes become parent classes in turn
  • When you have multiple levels of subclasses, you create an inheritance hierarchy
  • Classes higher in the hierarchy are called ancestor classes
  • Classes lower in the hierarchy are called descendent classes
  • A class can use the variables and methods of any of its superclasses
  • For example, a WeinerDog (below) uses the variables and methods provided by both Dog and Animal
  • Note that inheritance describes an is-a relationship
    • For instance: a Cat is an Animal
  • This is in contrast to the has-a relationship, where a class contains a reference to another class

Diagram Showing an Inheritance Hierarchy

  • The following diagram shows some classes from the Java API
  • From the diagram, you can see that a superclass may have more than one subclass
  • For instance, Dog has two subclasses: Rottweiler and WeinerDog

An inheritance diagram where Dog and Cat classes inherit from Animal and Rottweiler and Weiner Dog classes inherit from Dog

image source

Another Way to Draw Inheritance

  • There are many ways to draw inheritance diagrams
  • The following is another way to show the inheritance hierarchy for Container
  • Note how the superclass is always drawn higher than the subclass
    Animal
       |
       +--Cat
       |     |
       |     +--Siamese
       |
       +--Dog
             |
             +--Rottweiler
             |
             +--Chihuahua
    
    

Designing with Inheritance

  • Note in the inheritance diagram above that a Chihuahua is a type of Dog
  • When using inheritance in an application, it is important to keep "is a" in mind
  • Make sure a subclass has an is-a relationship with the superclass
    • A subclass must be a type of a superclass
  • Which of the following are valid is-a relationships?
    • Car ==> Vehicle
    • Car ==> Motorcycle
    • Student ==> Person
    • Student ==> College
  • Substitute the words "is a type of" for the arrow (==>)


Inheritance Example

  • To deriving a new class from an existing one, you use the extends clause
  • Syntax:
    [accessModifier] class SubclassName extends SuperclassName
  • A subclass can only extend one superclass
  • Java does not support multiple inheritance
  • Interfaces (discussed later) achieve much of the same effect

Example Superclass

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

public class Person {
private String name;

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

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

public String getName() {
return name;
}

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

public boolean samePerson(Person other) {
return (name.equalsIgnoreCase(other.name));
}

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

public void special() {
System.out.println("I am special");
}
}

Example Subclass

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

public class Student extends Person {
private int studentNumber;

public Student() {
super(); //call Person default constructor
studentNumber = 0;
}

public Student(String name, int number) {
super(name); //call Person one argument constructor
studentNumber = number;
}

public int getStudentNumber() {
return studentNumber;
}

public boolean sameStudent(Student other) {
return (super.samePerson(other) && other.studentNumber == studentNumber);
}

@Override public void printAttributes() {
super.printAttributes();
System.out.println("Student Number : "
+ studentNumber);
super.special();
}
}

Example Test Application

1
2
3
4
5
6
7
8
9
10
11
12
13
14

public class StudentApp {
public static void main(String[] args) {
Person al = new Person("Al");
Student xing = new Student("Xing", 55555);
Student buford = new Student("Buford", 11111);

System.out.println("Printing " + al.getName() + "'s information:");
al.printAttributes();
System.out.println("\nPrinting " + xing.getName() + "'s information:");
xing.printAttributes();
System.out.println("\nPrinting " + buford.getName() + "'s information:");
buford.printAttributes();
}
}

Adding Methods to Subclasses

  • We added a member variable to the Student subclass
    public class Student extends Person {
        private int studentNumber;
  • A Student has this attribute in addition to a name
    • name is inherited from Person
  • Also, we added a new instance method to the subclass:
    public int getStudentNumber() {
        return studentNumber;
    }
    
  • A Student has this method in addition to all the methods of the superclass


Overriding Methods

  • In addition to adding new members, we can change the way a method works for objects of a subclass
  • Changing the way a method works in a subclass is known as overriding a method
  • We overrode this method in our Student subclass
@Override public void printAttributes() {
        super.printAttributes();
        System.out.println("Student Number : "
                + studentNumber);
        super.special();
    }
  • Both superclass and subclass has a printAttributes method
  • Both methods have the same parameters (i.e. none)
    • Thus, they have the same signature
  • The method from the subclass overrides the superclass method
  • Note that a subclass method will NOT override a superclass method if the parameters are different
    • Would have different signatures
  • Note that calling this method has a different effect whether it is called for an object of type Person or an object of type Student:
System.out.println("Printing " + al.getName() + "'s information:");
al.printAttributes();
System.out.println("\nPrinting " + xing.getName() + "'s information:");
xing.printAttributes();
  • Sometimes people confuse overriding with overloading
  • See the table below for the similarities and differences

Overriding Verses Overloading

Overriding Overloading
  • Same method name
  • Same method name
  • Same signature
  • One method in superclass, one in subclass
  • Different signature
  • Both methods can be in same class


Constructors and Inheritance

  • Constructors are not inherited by a subclass
  • Instead, superclass constructors are called by the subclass constructor
  • Superclass constructors are called either implicitly or explicitly using super()

Examples of Subclass Constructors

  • Here is a no-parameter constructor for Student:
    public class Student extends Person {
        private int studentNumber;
        public Student() {
            super();
            studentNumber = 0;
        }
    ...
    
  • The first statement of the constructor is super() which calls the no-argument constructor of the superclass
  • After the superclass constructor finishes, this constructor then initializes the attribute studentNumber to 0
  • We could have left out the call to super() because Java automatically includes it if not explicitly stated
  • If you want to call a different constructor, then you use super() with arguments of the correct type:
    ...
    public Student(String name, int number) {
        super(name);
        studentNumber = number;
    }
    
  • This constructor passes the parameter name to the constructor of the superclass
  • After which the Student() constructor initializes the instance variable studentNumber
  • Note that super() must be first action in a constructor definition

Activity 11.1: An Employee Subclass (10 pts)

  • In the same folder where you saved Address.java, Person.java and PersonTest.java, add two more classes:
    • Employee.java
    • EmployeeTest.java
  • Copy and paste the below starter code into Employee.java:
/**
 * Employee.java extends Person.java
 * @author
 * CIS 36B, Activity 11.1
 */
public class Employee extends Person {
    private static int numEmployees = 0;
   
    private double salary;
    private String title;
   
    /**
     * Default constructor for the
     * Employee class. Calls the
     * default constructor of the
     * superclass and also initializes
     * salary and title to default
     * values
     */
    public Employee() {
      
    }
   
    /**
     * Multi-argument constructor for the
     * Employee class. Calls the
     * multi-argument constructor of the
     * superclass and also initializes
     * salary and title to the
     * specified values
     */
    public Employee(String name, int age, String gender, Address a, double salary, String title) {
       
    }
   
    /**
     * Returns the annual salary
     * @return the salary
     */
    public double getSalary() {
        return -1.0;
    }
   
    /**
     * Returns the title (position)
     * of the employee in the company
     * @return the title
     */
    public String getTitle() {
        return "";
    }
   
    /**
     * Returns the total number of employees
     * @return the number of employees
     */
    public static int getNumEmployees() {
        return -1;
    }
   
    /**
     * Updates the salary with a new value
     * @param salary the new salary
     */
    public void setSalary(double salary) {
       
    }
   
    /**
     * Updates the title of the employee
     * @param title the new title
     */
    public void setTitle(String title) {
       
    }
   
    /**
     * Increments numEmployees
     */
    public static void updateNumEmployees() {
      
    }
   
    /**
     * To String method for an employee
     * Calls the toString method of the
     * superclass and also appends the title
     * and salary information
     */
    @Override public String toString() {
        return "";
    }
}

  • Notice that this class is a subclass of Person (it extends Person).
  • Your job is to implement the method bodies of the above methods, as described in the method javadoc comments
  • When you have implemented all methods, copy and paste the below code into EmployeeTest.java, and make sure your output works as shown.
/**
 * EmployeeTest.java
 * @author
 * CIS 36B, Activity 11.1
 */

import java.util.Scanner;

public class EmployeeTest {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String name, gender, street, title;
        int age, number;
        double salary;
        Employee employee;
    
        System.out.print("Welcome!\n\nEnter your name: ");
        name = input.nextLine();
      
        System.out.print("Enter your age: ");
        age = input.nextInt();
      
        System.out.print("Enter your gender: ");
        gender = input.next();
       
        System.out.print("Enter the street number of your address: ");
        number = input.nextInt();
      
        System.out.print("Enter the name of your street: ");
        input.nextLine();
        street = input.nextLine();
       
        Address address = new Address(number, street);
       
        System.out.print("Enter your title in the company: ");
        title = input.nextLine();
       
        System.out.print("Enter your annual salary: ");
        salary = input.nextDouble();
       
      
        employee = new Employee(name, age, gender, address, salary, title);
        Employee.updateNumEmployees();
        System.out.println("\nYour Summary:\n" + employee);
      
        input.close();

    }
}

  • When your program works as shown in the sample output, upload Employee.java to Canvas.
Sample Output:

Welcome!

Enter your name: Rajya Chahal
Enter your age: 32
Enter your gender: F
Enter the street number of your address: 21899
Enter the name of your street: Summit Rd
Enter your title in the company: Vice President of Operations
Enter your annual salary: 185000

Your Summary:
Name: Rajya Chahal
Age: 32
Gender: F
Address: 21899 Summit Rd
Salary: $185000.0
Title: Vice President of Operations



2. Using Access Modifiers

  • You use the keywords public, private and protected to control access to class members
  • Controls access to class instance variables and methods

public Access: Interface Access

  • Least restrictive of all access modifiers
  • public fields and methods can be accessed from anywhere the class is accessible:
    public class MyClass {
        public double x;
        public void foo() {}
    }
    

private Access: Don't Touch That!

  • Most restrictive of all access modifiers
  • private fields and methods cannot be accessed from outside of the class
  • Good design practice to make all variables private and to provide accessor methods where needed
  • Auxiliary ("helper") methods are declared private often as well
  • Generally do not declare a class private -- how would you use it?
    public class MyClass {
        private double x;
        private void foo() {}
    }
    

protected Access: Inheritance Access

  • Accessible in the package of this class and any subclass of this class (which may be in other packages)
  • More restrictive than public accessibility but less restrictive than default
    public class MyClass {
        protected double x;
        protected void foo() {}
    }
    

Package Access: the Default

  • No access modifier: known as default or package accessibility
  • Only accessible to other classes in the same package (directory)
  • Less restrictive than private accessibility, but more restrictive than public or protected access
    class MyClass {
        double x;
        void foo() {}
    }
  • In our course, we will be using private and public access modifiers only as these are the most common 

Group Activity: Why will the below code not compile?

public class Parent {
    private String name;
    private int age;

    @Override public String toString() {
        return "Name: " + name + "\nAge: " + age;
    }
}

public class Child extends Parent {
    private double height;

    @Override public String toString() {
        return "Name: " + name + "\nAge: " + age + "\nHeight: " + height;
    }
}


Wrap Up: 

  • Answer the practice exam questions questions for this lesson on Canvas.

Upcoming Assignments:

  • Activity 11.1 due Tuesday at 11:59pm on Canvas
  • Lesson 11 Practice Exam Questions due Tuesday at 11:59pm on Canvas
  • Quiz 5 due Friday at 11:59pm on Canvas
  • Peer Reviews for Lesson 11 Practice Exam Questions due Saturday at 11:59pm on Canvas


~ Have a Great Day! ~