Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.

Similar presentations


Presentation on theme: "Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting."— Presentation transcript:

1 Lecture 8: Advanced OOP Part 2

2 Overview Review of Subtypes Interfaces Packages Sorting

3 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.

4 Solution public 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

5 Subtyping When we extend a class to create a sub-class, that sub- class can be used in place of its parent/super class We say the extended class is a subtype of its ancestor parent superclass We can access the parent using the keyword super the same way we can access ourself using this A 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

6 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!

7 Subtypes We can extend types (e.g., classes) by adding stuff to them to create subtypes The subtype/subclass has everything the supertype/superclass (its parent) has, but it has extra methods and data Two important concepts 1. Implementation Inheritance: A subclass inherits and can use all the methods and data fields of its parent 2. Inclusion Polymorphism: An instance of a subclass can be used anywhere an instance of the parent (superclass) can be used

8 Single Inheritance Consider a seaplane – it can be both a boat and a plane It would be nice to have it as a subclass of both Boats and Planes (multiple inheritance = multiple parents) Java DOES NOT permit this A class can have ONE direct parent Single inheritance = one parent only Seaplane must be a Boat OR a Plane Vehicle BoatsPlanes Seaplane

9 The Problem with Hierarchies PersonStudentFull-TimeUndergradGradPart-TimeUndergradGrad PersonStudentUndergradFull-TimePart-TimeGradFull-TimePart-Time

10 Interfaces A lot of the limitations of single inheritance can be bypassed using (Java) interfaces We 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 implementation An interface can be implemented by more than one class!

11 Example public interface flyable { public boolean isFlying(); public void raise (); public void lower (); } // end interface flyable public class flag implements flyable {... } public class kite implements flyable {... }

12 Multiple Interfaces Having a class implement an interface tells other programmers the things it can do E.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

13 Packages A package is a named collection of classes E.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 put package 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

14 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

15

16 Search Search is a very common need when programming A prototypical example would be, "does this array contain the value x" Efficiency generally tends to be an issue in search We search often We search large arrays To measure efficiency of search, we count the number of comparisons we perform – fewer is generally better!

17 Exercise Write 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) {... }

18 Improving Search How 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 log 2 (data.length) comparisons at most

19 Binary Search Example log 2 (4) = 2log 2 (8) = 3log 2 (16) = 4 log 2 (32) = 5log 2 (64) = 6log 2 (128) = 7 These are maximums, on average it is less! 2411131941578389

20 Binary Search – Implemented public 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()

21 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

22 Exercise Here 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); }

23 Solution public 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

24 Queues A 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 dequeue We 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.

25 Exercise Implement 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).

26 Solution public 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); } }

27

28 To Do Read Chapter 8 on Advanced OOP Read Chapter 9 on Exceptions We are almost done EVERYTHING up to 10.3 Do Assignment 8 in the lab today


Download ppt "Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting."

Similar presentations


Ads by Google