Inheritance

Alberto Ferrari
Ingegneria dell'Informazione, UniPR

Concepts

  • inheritance
  • subtyping
  • substitution
  • polymorphism

The network project

  • The network project implements a prototype of a small part of a social-network application like Facebook
  • Classes:
    • MessagePost
    • Photopost
    • NewsFeed

UML Class Diagram

(Unified Modeling Language)

UML

Classes in project

UML

Objects in project

UML

Look at source code ...

  • MessagePost source code and PhotoPost source code are very similar
  • They differ only in their details, such as some of their fields and corresponding accessors and the bodies of the display method
  • This application is not yet complete
  • We have defined the core of the application: the data structure that stores the essential information
  • There are several fundamental problems with our current solution. The most obvious one is code duplication

Inheritance

  • Inheritance allows us to define one class as an extension of another
  • A superclass is a class that is extended by another class
  • A subclass is a class that extends (inherits from) another class.
    • It inherits all fields and methods from its superclass
  • Inheritance is sometimes also called an is-a relationship
    • (a subclass is a specialization of a superclass)

UML Class Diagram

UML

We can say that “a message post is a post” and “a photo post is a post”

Hierarchy

UML

Classes that are linked through inheritance relationships form an inheritance hierarchy.

Java example

public class Post {
  private String username;  // username of the post’s author
  private long timestamp;
  private int likes;
  private ArrayList<String> comments;
  // Constructors and methods omitted.
}

public class MessagePost extends Post {
  private String message;
  // Constructors and methods omitted.
}

public class PhotoPost extends Post {
  private String filename; private String caption;
  // Constructors and methods omitted.
}

Inheritance and access rights

  • A subclass cannot access private members of its superclass
  • However, an object of a subclass may call any public methods defined in its superclass as if they were defined locally in the subclass
    • no variable is needed, because the methods are all part of the same object

example

  • Open the project network-v2 and look at classes source code

Constructors in subclasses

  • The constructor of a subclass must always invoke the constructor of its superclass as its first statement.
  • If the source code does not include such a call, Java will attempt to insert a call automatically.
  • super is a reference to the superclass

example

public class MessagePost extends Post {
  private String message; // an arbitrarily long, multi-line message
  /**
  * Constructor for objects of class MessagePost.
  * @param author    The username of the author of this post.
  * @param text      The text of this post.
  */
  public MessagePost(String author, String text) {
    super(author);
    message = text;
  }
  // Methods omitted.
}

Advantages of inheritance

  • Avoiding code duplication
  • Code reuse: Existing code can be reused. If a class similar to the one we need already exists, we can sometimes subclass the existing class and reuse some of the existing code rather than having to implement everything again
  • Easier maintenance: Maintaining the application becomes easier, a change to a field or a method that is shared between different types of subclasses needs to be made only once
  • Extendibility Using inheritance, it becomes much easier to extend an existing application in certain ways

Subtype

  • Subtype
    • The type defined by a subclass definition is a subtype of the type of its superclass
  • Variables may hold objects of their declared type or of any subtype of their declared type
  • Substitution
    • Subtype objects may be used wherever objects of a supertype are expected

example

Vehicle v1 = new Vehicle();
Vehicle v2 = new Car();
Vehicle v3 = new Bicycle();
Car c1 = new Vehicle(); // this is an error!

Exercise (a)

  • Assume that we have four classes: Person, Teacher, Student, and PhDStudent. Teacher and Student are both subclasses of Person. PhDStudent is a subclass of Student.
  • a. Which of the following assignments are legal, and why or why not?
    • Person p1 = new Student();
    • Person p2 = new PhDStudent();
    • PhDStudent phd1 = new Student();
    • Teacher t1 = new Person();
    • Student s1 = new PhDStudent();

Exercise (b)

  • b. Suppose that we have the following legal declarations and assignments:
    • Person p1 = new Person();
    • Person p2 = new Person();
    • PhDStudent phd1 = new PhDStudent();
    • Teacher t1 = new Teacher();
    • Student s1 = new Student();
  • Based on those just mentioned, which of the following assignments are legal, and why or why not?
    • s1 = p1;
    • s1 = p2;
    • p1 = s1;

Polymorphism

  • Variables holding object types in Java are polymorphic variables
  • The term “polymorphic” (literally, many shapes) refers to the fact that a variable can hold objects of different types (the declared type or any subtype of the declared type)

Casting

  • Sometimes the rule that we cannot assign from a supertype to a subtype is more restrictive than necessary
  • If we know that the supertype variable holds a subtype object, the assignment could actually be allowed. For example:
Vehicle v;
Car c = new Car();
v = c; // correct
c = v; // error  
c = (Car) v; // okay
  • The cast operator consists of the name of a type written in parentheses in front of a variable or an expression

example

Vehicle v;
Car c;
Bicycle b;
c = new Car();
v = c; // okay
b = (Bicycle) c; // compile time error!
b = (Bicycle) v; // runtime error!

Object class

  • All classes have a superclass
  • All classes that have no superclass declaration implicitly inherit from a class called Object

Object

Autoboxing - Unboxing

  • Autoboxing is performed automatically when a primitive-type value is used in a context requiring a wrapper type
    • es. from int to Integer
ArrayList<Integer> myList;
...
int val = 3;
myList.add(val);
  • Unboxing is the reverse operation
int myVal;
myVal = myList.remove(0);

Summary (1)

  • Inheritance allows us to define one class as an extension of another
  • A superclass is a class that is extended by another class
  • A subclass is a class that extends (inherits from) another class
    • inherits all fields and methods from its superclass
  • Classes that are linked through inheritance relationships form an inheritance hierarchy
  • The constructor of a subclass must always invoke the constructor of its superclass as its first statement. If the source code does not include such a call, Java will attempt to insert a call automatically.
  • Inheritance allows us to reuse previously written classes in a new context

Summary (2)

  • The type defined by a subclass definition is a subtype of the type of its superclass
  • Variables may hold objects of their declared type or of any subtype of their declared type.
  • Substitution: subtype objects may be used wherever objects of a supertype are expected
  • All classes with no explicit superclass have Object as their superclass
  • Autoboxing is performed automatically when a primitive-type value is used in a context requiring a wrapper type

Alberto Ferrari
Ingegneria dell'Informazione, UniPR
www.ce.unipr.it/~aferrari/