Inheritance

Inheritance

Attributes and methods can be inherited from one class to another

  • superclass (parent) - the class being inherited from
  • subclass (child) - the class that inherits from another class

Use the extends keyword

Superclass

Create a class called Person with the following instance variables:

  • First Name
  • Family Name
  • Birthdate

What public and private methods?

Make sure you do validation for setter methods.

Superclass – solution

import java.time.LocalDate;

public class Person {
    
    private String firstName;
    private String familyName;
    private int birthYear;
    private int birthMonth;
    private int birthDay;

    public Person(String first, String family) {
        firstName = first;
        familyName = family;
    }
    
    public void setBirthDate(int year, int month, int day) {
        LocalDate today = LocalDate.now(); 
        if (year > 1900 && year <= today.getYear()) birthYear = year;
        if (month > 0 && month <= 12) birthMonth = month;
        if (day > 0 && day <= 31) birthDay = day;
    }
    
    public String getBirthDate() {
        String month;
        if (birthMonth < 10) month = "0" + birthMonth;
        else month = "" + birthMonth;
        return birthYear + "/" + month + "/" + birthDay;
    }
    
    public String getFirstName() {
        return firstName;
    }
    
    public String getFamilyName() {
        return familyName;
    }
    
    public void print() {
        System.out.print(firstName + " " + familyName);
        System.out.println(" born on " + getBirthDate());
    }
    
}

Subclass

Create a class called Student that extends the Person class. Add the following instance variables:

  • Admissions Year
  • Graduation Year
  • Major
  • Email address (or only netID)

What public and private methods?

Write a constructor method, invoke base-class constructor using super keyword

Subclass – solution

import java.time.LocalDate;

public class Student extends Person {
    private int admissionYear;
    
    public Student(String first, String family,
                   int admissionYear) {
        // invoke base-class constructor
        super(first, family);
        LocalDate today = LocalDate.now(); 
        if (admissionYear > 1900 && admissionYear <= today.getYear()) 
            this.admissionYear = admissionYear;
    }
    
    public int getAdmission() {
        return admissionYear;
    }
    
    // override annotation
    @Override public void print() {
        super.print();
        System.out.println("Admitted in " + admissionYear);
    }

}

Polymorphism

poly means many, morphs means forms

one interface with multiple implementations

Polymorphism in java:

  • Compile-time Polymorphism: Method overloading
  • Runtime Polymorphism: Method overriding

UML diagram

We will be using Unified Modeling Language (UML) diagrams to understand and plan classes and their inheritance.

  • add name of the class at the top of each box in the diagram
  • use +/- for public/private
  • include instance variables, methods (including constructors) with parameters

I use the UML class template from Lucidcharts (available through google drive)

UML diagram example

Implementation example

Animal.java

public class Animal {
    private String species;
    private String genus;
    private String family;
    
    public Animal (String s, String g, String f) {
        species = s;
        genus = g;
        family = f;
    }
    
    public String toString() {
        String message;
        message = "The " + species;
        message += " of genus " +  genus;
        message += " and family " + family;
        return message;
    }

}

Implementation example

Cat.java

public class Cat extends Animal {
    public Cat() {
        super("Cat", "Felis", "Felidae");
    }
    
    public String makesSound() {
        return "meow";
    }

}

Implementation example

public class GetAnimals {

    public static void main(String[] args) {
        Cat garfield = new Cat();
        System.out.println(garfield.toString());
    }

}

Quiz 3

current time

abstract superclass

An abstract class cannot be instantiated (an error is thrown)

Animal animal = new Animal(); // Error: Animal is abstract

An abstract class must be subclassed

Methods in an abstract class can also be abstract – similar to an interface

abstract example implementation

public abstract class Animal {
    private String species;
    private String genus;
    private String family;
    
    public Animal (String s, String g, String f) {
        species = s;
        genus = g;
        family = f;
    }
    
    public abstract String makesSound();
    
    public String toString() {
        String message;
        message = "The " + species;
        message += " of genus " +  genus;
        message += " and family " + family;
        message += " makes this sound: ";
        message += makesSound();
        return message;
    }

}

protected keyword

The private access modifier specifies the variable can only be accessed in its own class

The protected access modifier specifies that the variable can only be accessed by a subclass of its class

protected implementation

public abstract class Animal {
    protected String species;
    protected String genus;
    protected String family;
    
    public Animal () {}
    
    public abstract String makesSound();
    
    public String toString() {
        String message;
        message = "The " + species;
        message += " of genus " +  genus;
        message += " and family " + family;
        message += " makes this sound: ";
        message += makesSound();
        return message;
    }

}

protected implementation

public class Cat extends Animal {
    public Cat() {
        species = "Cat";
        genus = "Felis";
        family = "Felidae";
    }
    
    public String makesSound() {
        return "meow";
    }

}

Updated UML diagram

Update the UML diagram

The classes and inheritance relationships that we worked with so far has been simplified.

With the table mates, improve on the Animal superclass and its subclasses.

  • What other instance variables should you include?
  • What about methods?

You are to submit your group UML diagram to gradescope for the short assignment 6. Do not submit my UML diagram with annotations, create your own.

UML diagram presentations