Inheritance is a method that creates a new class that builds on an existing one. It models real-life inheritance, with an ancestor-descendant tree of classes.
Key concepts
HAS-A versus IS-A. A car has a tire, so if you're modeling a car with a
Car
class, you might have a tire as a member variable. A Chevy Cavalier is a car, so if you create aChevyCavalier
class it might inherit fromCar
.Encapsulation within a class hierarchy.
private
members can't be touched by any other class.public
members can be touched by everyone.protected
members can be touched by subclasses.There's actually a fourth category of encapsulation: if you don't specify any of the above, the default is that any class in the same package can access the member.
super
. When defining methods in a subclass, you might need to access functionality in the parent class. Thesuper
keyword is used to get access to any method that's been overridden in the subclass, or to call the parent constructor.Object
: the root of the class hierarchy in Java. Every object in Java is an instance ofObject
. So if you have a variable of typeObject
, that variable can refer to any object (even if it's aString
or any other class).
Examples
See the inheritance-examples project in the course materials.
Readings
Read the "Inheritance" chapter in the book.
Homework
Starting reviewing for the exam. Do as many problems from the book as you can. Example exam questions will be posted soon, but you can take a look at these exams from 130 for examples of the question format.
Don't forget that you can bring one sheet of paper filled front and back with notes. You won't be responsible for knowing particular class names and methods, but you should be comfortable using all basic syntax, statements, and primitive types we've covered.