Inheritance
no longer on AP Exam, but still an important concept that will be use in many of your labs
Inheritance
Classes can inherit
Inheritance: A way to form new classes based on existing classes, taking on their attributes/behavior.
Parent class or Superclass
Child class or Subclass
2
Syntax
A class can extend another class by using the keyword extends then the name of the class it is extending.
Below, Employee extends Person.
public class Person{
private String name;
public Person(String theName){
this.name = theName;
}
…
}
public class Employee extends Person{
// not shown
}
3
is-a relationship
When one class inherits from another, we can say that it is the same kind of thing as the parent class (the class it inherits from).
This is called a is-a relationship.
�
class Vehicle {}
class Car extends Vehicle {}
class Motorcyle extend Vehicle {}
4
UML
A UML (Unified Modeling Language) class diagram shows classes and the relationships between the classes as seen in Figure 1.
An open triangle points to the parent class. The parent class for Car and Motorcycle is Vehicle. The Vehicle class has two child classes or subclasses: Car and Motorcycle.
5
Why Use Inheritance
Generalization
For example, if you wrote two classes Customers and Employees and both of which have instance variables name and address, then it makes sense write the general Person class with the variables name and address and have Customers and Employees inherit from Person.
Specialization
Suppose that you already wrote the Person class and you want a Customer class that has all of the attributes of Person but also has a credit card. Or you want an Employee class that has an additional instance variable for id.
See UML on the next page.
�
6
UML
7
super()
Subclasses
How do you initialize inherited private variables if you don’t have direct access to them in the subclass?
keyword super
8
Person Class
Below is the Person class. We will create an Employee class which extends this class.
class Person{
private String name;
public Person(String theName){
this.name = theName;
}
public String getName(){
return name;
}
// other methods not shown
}
9
Error!
The subclass constructor cannot directly initialize the super class' private variables.
public class Employee extends Person{
private int id;
public Employee(String name, int id){
this.name = name; // error, name is private
this.id = id;
}
public int getId(){
return id;
}
// other methods not shown
}
10
Fixed!
The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters.
super() must be called on the first line of the constructor!
public class Employee extends Person{
private int id;
public Employee(String name, int id){
super(name); // call Person's constructor
this.id = id; // to initialize name variable
}
// other methods not shown
}
Now each Employee object has an id variable in addition to the inherited name variable.
11
Main Class
public class Main{
public static void main(String[] args){
Person p = new Person("Mike");
System.out.println(p.getName()); // Mike
Employee emp = new Employee("Dani", 123);
System.out.println(emp.getName()); // Dani
System.out.println(emp.getId()); // 123
Person p1 = new Employee("Mike", 11);
// correct, every Employee is a Person.
Employee p2 = new Person("Mike");
// incorrect, not every Person is an Employee
}
}
}
12
Constructors
See the next slide for an example of a common constructor error.�
13
Constructor Error
If a subclass has no call to a superclass constructor using super as the first line in a subclass constructor then the compiler will automatically add a super() call as the first line in a constructor.
Find the error.
class Person{
// Suppose this class has only this one constructor.
public Person(String theName){…}
}
public class Employee extends Person{
private int id;
public Employee(String name, int id){
this.id = id;
}
}
implicitly call super() since subclass constructor has no super() call.
But parent class Person has no default constructor. Error!
14
Fix # 1
The simplest way to fix the previous error is to always explicitly call super with the appropriate parameters as the first line in every subclass constructor.
class Person{
// Suppose this class has only this one constructor.
public Person(String theName){…}
}
public class Employee extends Person{
private int id;
public Employee(String name, int id){
super(name);
this.id = id;
}
}
It is best to explicitly call super() with the apppropriate parameters.
15
Fix # 2
Another way to fix the previous error is to provide a default(no argument) constructor in the parent class.
class Person{
public Person(){…}
public Person(String theName){…}
}
public class Employee extends Person{
private int id;
public Employee(String name, int id){
this.id = id;
}
}
implicitly call super() since subclass constructor has no call. And since parent class does have a default construtor, no error!
16
Levels of Inheritance
Multiple levels of inheritance in a hierarchy are allowed.
public class Person{ // implementation not shown}
public class Employee extends Person{ // not shown}
public class Lawyer extends Employee{ // not shown}
Find the error. Errors in red below.
public class Main(){
public static void main(String[] args){
Person p1 = new Employee("Mike", 11);
Employee p2 = new Lawyer("John", 22);
Lawyer p3 = new Person("Katie");
Lawyer p4 = new Employee("Jim", 33);
Person p5 = new Lawyer("Michele", 44);
Employee p6 = new Person("Jack");
}
}
17
Inherited Methods
A subclass inherits all public methods from its superclass, and these methods remain public in the subclass.
But, we also usually add more methods or instance variables to the subclass.
class Person{
…
public String getName(){…}
}
public class Employee extends Person{
…
public void printJobDescription(){…}
}
Employee inherits getName() from Person.
Employee cannot access name directly but can access it indirectly through getName and setName, etc…
printJobDescription() is a new method in Employee that is not in Person.
18
Sample Question 1
Consider the inheritance hierarchy of the classes below.
Which of the following declarations will cause an error? You may assume that each of the classes shown has a default constructor.
Select single answer choice.
A I only
B II only
C III only
D I and II only
E II and III only
Answer: B
Declaration II fails because it fails this test: LibraryItem is-a Book? No.
Notice that declarations I and II pass the is-a test:
LibraryItem is-a LibraryItem? Yes.
CD is-a LibraryItem? Yes.
Move this box to see the answer
19
Sample Question 2
Consider the inheritance hierarchy of the classes below.
Answer: A
Because the CD and Book classes are subclasses of LibraryItem, each inherits getPrice and can call it in a client class. Each of the other choices has a specific function, none of which is illustrated in the code segment. An overridden method is redefined in a subclass. (This is not true here, because you are given that getPrice is defined only in the superclass.) Polymorphism operates only when methods are overridden: At run time, the actual subclass instance is bound to the correct version of the method. An overloaded method has the same name as another method in the class or subclass but a difference signature. A mutator method is one that changes the state of an object. The getPrice method is an accessor.
Move this box to see the answer
Suppose that, of the three classes shown in the diagram, only the LibraryItem class has a method called getPrice defined in it, whose specification is as follows.
�Now consider the following declaration that appears in a client program.
Assume that libraryList is initialized with LibraryItem objects. Consider the following code segment that computes the total cost of all items stored in libraryList.
�The use of getPrice in this code segment is an example of (Select single answer choice)�A an inherited method.�B an overridden method.�C polymorphism.�D an overloaded method.�E a mutator method.
20
Sample Question 3
Answer: E
Statement I works because BalletDancer inherits the leap method. Statement III works because Dancer contains the leap method. Statement II fails because Dancer does not contain a glide method. There will be a compile-time error. The statement can be fixed with a cast:
Consider the class definitions to the left. A client program has the following declarations.
Which of the following statements is (are) valid?
Move this box to see the answer
21
Sample Question 4
Answer: E�None of these declarations will get past the compiler. Declaration I fails because the PosInt class has no default constructor. Declaration II fails for the same reason: If PosInt had a default constructor, the following code would automatically be placed in the subclass EvenPosInt.
Which of the following declarations in a client class would cause an error?
Declaration III fails because the superclass constructors are not inherited. You need to add the following constructor code to EvenPosInt to make declaration III work.
But this only works if there is a default constructor in the superclass!
Move this box to see the answer
22