Upload
gregory-ryan
View
223
Download
0
Embed Size (px)
DESCRIPTION
Exercise public class flag { private boolean raised; // Constructor public flag () { raised = false; } // Public interface methods public boolean isFlying() { return (raised); } public void raise () { raised = true; } public void lower () { raised = false; } } // end class flag Add a copy constructor to this class. That is, add a second constructor that takes a flag object and returns a copy of the object.
Citation preview
CSCI1227Computer Programming and
Problem Solving
Lecture 8: Advanced OOP Part 2
OverviewReview of SubtypesInterfacesPackagesSorting
Exercisepublic class flag { private boolean raised; // Constructor public flag () { raised = false; } // Public interface methods public boolean isFlying() { return (raised); } public void raise () { raised = true; } public void lower () { raised = false; }} // end class flag
Add a copy constructor to this class. That is, add a second constructor that takes a flag object and returns a copy of the object.
Solutionpublic class flag { private boolean raised; // Constructor public flag () { raised = false; } public flag (flag f) { this.raised = f.raised; } // Public interface methods public boolean isFlying() { return (raised); } public void raise () { raised = true; } public void lower () { raised = false; }} // end class flag
SubtypingWhen we extend a class to create a sub-class, that
sub-class can be used in place of its parent/super classWe say the extended class is a subtype of its ancestor
parent superclassWe can access the parent using the keyword super
the same way we can access ourself using thisA child has its own instance (copy) of the parent class
and is said to inherit the methods and data of the parent
The child can override the parents methods with its own versions
Which One?public class person { ... }public class student extends person { ... }
person p = new student();p.display();
Is display called for a person (the type of p) or for a student (the type of the object stored in p)?
It is called for student. It is the OBJECT not the storage location that matters here!
SubtypesWe can extend types (e.g., classes) by adding stuff to
them to create subtypesThe subtype/subclass has everything the
supertype/superclass (its parent) has, but it has extra methods and data
Two important concepts1. Implementation Inheritance: A subclass inherits and
can use all the methods and data fields of its parent2. Inclusion Polymorphism: An instance of a subclass
can be used anywhere an instance of the parent (superclass) can be used
Single InheritanceConsider a seaplane – it can be both a boat
and a planeIt would be nice to have it as a subclass of
both Boats and Planes (multiple inheritance = multiple parents)
Java DOES NOT permit thisA class can have ONE direct parentSingle inheritance = one parent onlySeaplane must be a Boat OR a Plane
Vehicle
Boats Planes
Seaplane
The Problem with HierarchiesPerson
Student
Full-Time
Undergrad Grad
Part-Time
Undergrad Grad
Person
Student
Undergrad
Full-Time Part-Time
Grad
Full-Time Part-Time
InterfacesA lot of the limitations of single inheritance
can be bypassed using (Java) interfacesWe say that an ADT has an interface (how its
used) and an implementation.It is possible to store the interface in its own
file and separate it from the implementationAn interface can be implemented by more
than one class!
Examplepublic interface flyable { public boolean isFlying(); public void raise (); public void lower ();} // end interface flyable
public class flag implements flyable { ... }public class kite implements flyable { ... }
Multiple InterfacesHaving a class implement an interface tells
other programmers the things it can doE.g., since it implements flyable,
programmers know that flag has a raise method
A class can implement MORE THAN ONE interface
In this way, we could have a floatable interface, and thus a seaplane could implement both flyable and floatable
Interfaces can also be extended
PackagesA package is a named collection of classesE.g., java.util and java.io are packages
(the . is just part of the name here!)If you want a class to be part of a package
you must putpackage name;
as the first line of code (comments and blank lines may come before it since they are not code)
The package may then be imported by other classes and its classes used
Packages are needed when code is put into a different directory
Normally Java has been looking in the current directory for all your classes
You use a package if you want to move something to a different directory
The jvm has a classpath variable that it uses to search for packages
Directories
SearchSearch is a very common need when
programmingA prototypical example would be, "does this
array contain the value x"Efficiency generally tends to be an issue in
searchWe search oftenWe search large arraysTo measure efficiency of search, we count the
number of comparisons we perform – fewer is generally better!
ExerciseWrite a method called search that returns the index
value of any occurrence of val in the array data.
public static int search (int[] data, int val) { ... }
Improving SearchHow can we improve this?Well, what if the data was sorted ...Check the middle item and then we know if
the value is above or below that – One check and we've removed half of the possible values!
Check the middle of the remaining range, and we can delete 1/2 the remaining values or 1/4 of the total values
If we do this to completion, we will take at most log2(data.length) comparisons at most
Binary Search Examplelog2(4) = 2 log2(8) = 3 log2(16) = 4
log2(32) = 5 log2(64) = 6 log2(128) = 7
These are maximums, on average it is less!
2 4 11 13 19 41 57 83 89
Binary Search – Implementedpublic static int bsearch (int[] data, int val) { int lo = 0, hi = data.length – 1, mid;
while (lo <= hi) { mid = (lo + hi) / 2; if (val < data[mid]) { hi = mid - 1; } else if (val > data[mid]) { lo = mid + 1; } else { return (mid); } } return (-1) ;} // end bsearch()
The Catch ...Binary search really is far more efficient,
there's not really anything superior when you have sorted data
But, we have to add the cost of the sort to the search!
If we search a lot, the sort cost is amortized over many searches and is not very significant
If we search once, particularly on small data sets, then linear search can be more efficient
Halving the problem is a popular programming technique that can be used in many places
ExerciseHere is a search method. Modify it so that it
throws an exception rather than returning -1 if the value isn't found.
public static int search (int[] data, int val) {
for (int i = 0; i < data.length; i++) { if (data[i] == v) return (i); } return (-1);}
Solutionpublic static int search (int[] data, int val) throws Exception { for (int i = 0; i < data.length; i++) { if (data[i] == v) return (i); } throw new Exception ("Search failure");} // end search
QueuesA Queue is an ADT that functions like a bank
line-up. Where a stack was FILO (first in, last out), a
queue is FIFO (first in, first out)Instead of push and pop, the interface
methods are enqueue and dequeueWe usually implement a queue using a
"circular array"That is, when we hit the back of the array, we
wrap around to the front of the array.
ExerciseImplement a queue given the following interface:
public interface FIFO { public void enqueue(int val) throws Exception; public int dequeue() throws Exception; public int count(); }
count returns the number of items currently in the queue.Add a constructor that initialises an empty queue to a
provided size. (Note, interfaces in Java can't contain constructors).
Solutionpublic class queue implements FIFO { private int numItems, head, tail; private int[] data; public queue (int size) { data = new int[size]; head = 0; tail = 0; numItems = 0; } public void enqueue(int val) throws Exception { if (numItems == data.length) throw Exception ("Overflow"); data[tail++] = val; numItems += 1; tail = tail % data.length; } public int dequeue() throws Exception { int v; if (numItems == 0) throw new Exception ("Underflow"); v = data[head++]; head = head % data.length; numItems -= 1; return (v); } public int count() { return (n); } }
To DoRead Chapter 8 on Advanced OOPRead Chapter 9 on ExceptionsWe are almost done EVERYTHING up to 10.3Do Assignment 8 in the lab today