Chapter 6. Implementation of Inheritance and Polymorphism
Chapter 6. Implementation of Inheritance and Polymorphism
•Chapter 6
1
Object Oriented Programming Course VKU
Inheritance
Object Oriented Programming Course VKU
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
• is-a relationship: Each object of the subclass also "is a(n)" object of the superclass and can
be treated as one.
Object Oriented Programming Course VKU
Inheritance syntax
public class name extends superclass {
• Example:
public class Lawyer extends Employee {
...
}
Overriding Methods
• override: To write a new version of a method in a subclass that replaces the
superclass's version.
• No special syntax required to override a superclass method.
Just write a new version of it in the subclass.
Subclasses and
public class Employee {
fields
private double salary;
...
}
Protected fields/methods
protected type name; // field
• The short explanation: Once we write a constructor (that requires parameters) in the
superclass, we must now write constructors for our employee subclasses as well.
Object Oriented Programming Course VKU
• Example:
public class Lawyer extends Employee {
public Lawyer(int years) {
super(years); // calls Employee c'tor
}
...
}
• The super call must be the first statement in the constructor.
Object Oriented Programming Course VKU
Polymorphism
Object Oriented Programming Course VKU
Polymorphism
• polymorphism: Ability for the same code to be used with different types of
objects and behave differently with each.
• You can call any methods from the Employee class on ed.
Polymorphic parameters
• You can pass any subtype of a parameter's type.
public static void main(String[] args) {
Lawyer lisa = new Lawyer();
Secretary steve = new Secretary();
printInfo(lisa);
printInfo(steve);
}
public static void printInfo(Employee e) {
System.out.println("pay : " + e.getSalary());
System.out.println("vdays: " + e.getVacationDays());
System.out.println("vform: " + e.getVacationForm());
System.out.println();
}
OUTPUT:
pay : 50000.0 pay : 50000.0
vdays: 15 vdays: 10
vform: pink vform: yellow
Object Oriented Programming Course VKU
Output:
pay : 50000.0 pay : 60000.0
vdays: 15 vdays: 10
pay : 50000.0 pay : 55000.0
vdays: 10 vdays: 10
Object Oriented Programming Course VKU
Casting references
• A variable can only call that type's methods, not a subtype's.
Employee ed = new Lawyer();
int hours = ed.getHours(); // ok; in Employee
ed.sue(); // compiler error
• The compiler's reasoning is, variable ed could store any kind of employee, and not all kinds
know how to sue .
• You can cast only up and down the tree, not sideways.
Lawyer linda = new Lawyer();
((Secretary) linda).takeDictation("hi"); // error
Interfaces
Object Oriented Programming Course VKU
Shapes example
• Consider the task of writing classes to represent 2D shapes such as Circle,
Rectangle, and Triangle.
Common behavior
• Suppose we have 3 classes Circle, Rectangle, Triangle.
• Each has the methods perimeter and area.
• We'd like our client code to be able to treat different kinds of shapes in the same
way:
• Write a method that prints any shape's area and perimeter.
• Create an array to hold a mixture of the various shape objects.
• Write a method that could return a rectangle, a circle, a triangle, or any other kind of
shape.
• Make a DrawingPanel display many shapes on screen.
Object Oriented Programming Course VKU
Interfaces
• interface: A list of methods that a class can promise to implement.
• Inheritance gives you an is-a relationship and code sharing.
• A Lawyer can be treated as an Employee and inherits its code.
Interface syntax
public interface name {
public type name(type name, ..., type name);
public type name(type name, ..., type name);
...
public type name(type name, ..., type name);
}
Example:
public interface Vehicle {
public int getSpeed();
public void setDirection(int direction);
}
Object Oriented Programming Course VKU
Shape interface
// Describes features common to all shapes.
public interface Shape {
public double area();
public double perimeter();
}
• Saved as Shape.java
Implementing an interface
public class name implements interface {
...
}
• Example:
public class Bicycle implements Vehicle {
...
}
Object Oriented Programming Course VKU
Interface requirements
public class Banana implements Shape {
// haha, no methods! pwned
}
• If we write a class that claims to be a Shape but doesn't implement area and
perimeter methods, it will not compile.
Interfaces + polymorphism
• Interfaces benefit the client code author the most.
• they allow polymorphism
(the same code can work with different types of objects)
Abstract Classes
Object Oriented Programming Course VKU
Common code
• Notice that some of the methods are implemented the same way in both the
array and linked list classes.
• add(value)
• contains
• isEmpty
• Abstract classes can claim to implement an interface without writing its methods;
subclasses must implement the methods.
public abstract class Empty implements List {} // ok
Inner Classes
Object Oriented Programming Course VKU
Inner classes
• inner class: A class defined inside of another class.
• can be created as static or non-static
• we will focus on standard non-static ("nested") inner classes
• usefulness:
• inner classes are hidden from other classes (encapsulated)
• inner objects can access/modify the fields of the outer object
Object Oriented Programming Course VKU
• Only this file can see the inner class or make objects of it.
• Each inner object is associated with the outer object that created it, so it can access/modify
that outer object's methods/fields.
• If necessary, can refer to outer object as OuterClassName.this
Object Oriented Programming Course VKU
public ArrayIterator() {
index = 0;
}
public E next() {
index++;
return get(index - 1);
}
Collections
Object Oriented Programming Course VKU
Collections
• collection: an object that stores data; a.k.a. "data structure"
• the objects stored are called elements
• some collections maintain an ordering; some allow duplicates
• typical operations: add, remove, clear, contains (search), size
Lists
• list: a collection storing an ordered sequence of elements
• each element is accessible by a 0-based index
• a list has a size (number of elements that have been added)
• elements can be added to the front, back, or elsewhere
• in Java, a list can be represented as an ArrayList object
Object Oriented Programming Course VKU
Idea of a list
• Rather than creating an array of boxes, create an object that represents a "list" of
items. (initially an empty list.)
[]
• The list object keeps track of the element values that have been added to it, their
order, indexes, and its total size.
• Think of an "array list" as an automatically resizing array object.
• Internally, the list is implemented using an array and a size field.
Object Oriented Programming Course VKU
ArrayList methods 2
addAll(list) adds all elements from the given list to this list
addAll(index, list) (at the end of the list, or inserts them at the given index)
contains(value) returns true if given value is found somewhere in this list
containsAll(list) returns true if this list contains every element from given list
equals(list) returns true if given other list contains the same elements
iterator() returns an object used to examine the contents of the list
listIterator()
lastIndexOf(value) returns last index value is found in list (-1 if not found)
remove(value) finds and removes the given value from this list
removeAll(list) removes any elements found in the given list from this list
retainAll(list) removes any elements not found in given list from this list
subList(from, to) returns the sub-portion of the list between
indexes from (inclusive) and to (exclusive)
toArray() returns the elements in this list as an array
Object Oriented Programming Course VKU
front back
top 3 remove, peek add
1 2 3
2
queue
bottom 1
stack
Object Oriented Programming Course VKU
Stacks
• stack: A collection based on the principle of adding elements and retrieving them
in the opposite order.
• Last-In, First-Out ("LIFO")
• The elements are stored in order of insertion,
but we do not think of them as having indexes.
• The client can only add/remove/examine
the last element added (the "top").
push pop, peek
Class Stack
Stack<E>() constructs a new stack with elements of type E
push(value) places given value on top of stack
pop() removes top value from stack and returns it;
throws EmptyStackException if stack is empty
peek() returns top value from stack without removing it;
throws EmptyStackException if stack is empty
size() returns number of elements in stack
isEmpty() returns true if stack has no elements
Stack<Integer> s = new Stack<Integer>();
s.push(42);
s.push(-3);
s.push(17); // bottom [42, -3, 17] top
System.out.println(s.pop()); // 17
• Stack has other methods, but you should not use them.
Object Oriented Programming Course VKU
Queues
• queue: Retrieves elements in the order they were added.
• First-In, First-Out ("FIFO")
• Elements are stored in order of
insertion but don't have indexes.
• Client can only add to the end of the
queue, and can only examine/remove
the front of the queue.
front back
remove, peek add
1 2 3
queue
• basic queue operations:
• add (enqueue): Add an element to the back.
• remove (dequeue): Remove the front element.
• peek: Examine the front element.
Object Oriented Programming Course VKU
• IMPORTANT: When constructing a queue you must use a new LinkedList object
instead of a new Queue object.
Object Oriented Programming Course VKU
Queue idioms
• As with stacks, must pull contents out of queue to view them.
// process (and destroy) an entire queue
while (!q.isEmpty()) {
do something with q.remove();
}
• We don't know exactly how a stack or queue is implemented, and we don't need
to.
• We just need to understand the idea of the collection and what operations it can perform.
(Stacks are usually implemented with arrays; queues are often implemented using another
structure called a linked list.)
Object Oriented Programming Course VKU
• You choose the optimal implementation for your task, and if the rest of your code is written
to use the ADT interfaces, it will work.
Object Oriented Programming Course VKU
Sets
• set: A collection of unique values (no duplicates allowed)
that can perform the following operations efficiently:
• add, remove, search (contains)
"the"
"if" "of"
set.contains("to") "to"
"down" "from" true
"by" "she"
set.contains("be") "you" false
"in"
"why" "him"
set
Object Oriented Programming Course VKU
Set implementation
• in Java, sets are represented by Set interface in java.util
Set methods
List<String> list = new ArrayList<String>();
...
Set<Integer> set = new TreeSet<Integer>(); // empty
Set<String> set2 = new HashSet<String>(list);
Set operations
addAll(collection) adds all elements from the given collection to this set
containsAll(coll) returns true if this set contains every element from given set
equals(set) returns true if given other set contains the same elements
iterator() returns an object used to examine set's contents (seen later)
removeAll(coll) removes all elements in the given collection from this set
retainAll(coll) removes elements not found in given collection from this set
toArray() returns an array of the elements in this set
Object Oriented Programming Course VKU
• Provides a clean syntax for looping over the elements of a Set, List, array, or
other collection
Set<Double> grades = new HashSet<Double>();
...
Map concepts
• a map can be thought of as generalization of a tallying array
• the "index" (key) doesn't have to be an int
Map implementation
• in Java, maps are represented by Map interface in java.util
• A map requires 2 type parameters: one for keys, one for values.
Map methods
put(key, value) adds a mapping from the given key to the given value;
if the key already exists, replaces its value with the given one
get(key) returns the value mapped to the given key (null if not found)
containsKey(key) returns true if the map contains a mapping for the given key
remove(key) removes any existing mapping for the given key
clear() removes all key/value pairs from the map
size() returns the number of key/value pairs in the map
isEmpty() returns true if the map's size is 0
toString() returns a string such as "{a=90, d=60, c=70}"
Using maps
• A map allows you to get from one half of a pair to the other.
• Remembers one piece of information about every index (key).
// key value
put("Joe", "206-685-2181")
Map
• Later, we can supply only the key and get back the related value:
Allows us to ask: What is Joe's phone number?
get("Joe")
Map
"206-685-2181"
Object Oriented Programming Course VKU
"Joe" true
Set
false
• Reminder:
public class Foo implements Comparable<Foo> {
…
public int compareTo(Foo other) {
// Return positive, zero, or negative number
}
}