03-inheritance
03-inheritance
Lecture 3
Inheritance
2
The toString method
• Tells Java how to convert an object into a String
ArrayIntList list = new ArrayIntList();
System.out.println("list is " + list);
// ("list is " + list.toString());
• Syntax:
public String toString() {
code that returns a suitable String;
}
4
Multiple constructors
• existing constructor:
public ArrayIntList() {
elementData = new int[1000];
size = 0;
}
5
this keyword
• this : A reference to the implicit parameter
(the object on which a method/constructor is called)
• Syntax:
– To refer to a field: this.field
– To call a method:
this.method(parameters);
– To call a constructor this(parameters);
from another constructor:
6
Revised constructors
public ArrayIntList() {
this(1000); // calls other constructor
}
7
Exercise
• Write a class called StutterIntList.
– Its constructor accepts an integer stretch parameter.
– Every time an integer is added, the list will actually add
stretch number of copies of that integer.
• Example usage:
StutterIntList list = new StutterIntList(3);
list.add(7); // [7, 7, 7]
list.add(-1); // [7, 7, 7, -1, -1, -1]
list.add(2, 5); // [7, 7, 5, 5, 5, 7, -1, -1, -1]
list.remove(4); // [7, 7, 5, 5, 7, -1, -1, -1]
System.out.println(list.getStretch()); // 3
8
Inheritance
• inheritance: Forming new classes based on existing
ones.
– a way to share/reuse code between two or more classes
– superclass: Parent class being extended.
– subclass: Child class that inherits behavior from
superclass.
• gets a copy of every field and method from superclass
9
Inheritance syntax
public class name extends superclass {
– Example:
10
Overriding methods
• override: To replace a superclass's method by writing
a new version of that method in a subclass.
– No special syntax is required to override a method.
Just write a new version of it in the subclass.
11
super keyword
• Subclasses can call overridden methods with super
super.method(parameters)
– Example:
public class Lawyer extends Employee {
// give Lawyers a $5K raise (better)
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + 5000.00;
}
}
– Example:
public class Lawyer extends Employee {
public Lawyer(int years) {
super(years); // calls Employee constructor
}
...
}