inheritance polymorphism
play

Inheritance Polymorphism Can create new classes by extending others - PDF document

Inheritance Polymorphism Can create new classes by extending others Literally: the ability to assume many forms Subclass inherits all members of superclass OOP idea: a superclass reference can refer to But cannot directly


  1. Inheritance Polymorphism � Can create new classes by extending others � Literally: the ability to assume many forms – Subclass inherits all members of superclass � OOP idea: a superclass reference can refer to � But cannot directly access private members many types of subclass objects – Can add new fields and new methods – Each object may behave differently – if subclasses – Can override existing methods override methods – Cannot remove fields or methods � Imagine a Shape class with a draw() method � Can only extend one other class in Java – Subclasses Circle , Triangle , … override draw() – Makes for clear hierarchies (less complication) – Then say void picture(Shape s) { s.draw(); } – But indirectly extend superclass’s parent, … � Object s is a Shape or a subclass of Shape � All Java classes are descendants of Object � Relies on “dynamic method binding” � Note: composition another way to reuse code Abstract classes and interfaces More about interfaces � Abstract class has one or more abstract methods � All methods are public abstract – omit explicit modifiers by convention – Subclasses must implement these methods � Constants okay too – Cannot instantiate – objects must be subclass objects – All public static final – omitted by convention – Subclasses inherit implementation and interface – Must be initialized when declared � A Java interface has no implementation at all � Can extend, just like classes – But okay to extend more than one: – e.g., “… implements Comparable ” means the class public interface SerializableRunnable responds to compareTo(Object other) extends java.io.Serializable, Runnable – A class may implement multiple interfaces � Tend to be much more flexible than classes as a way to unite objects in system designs � No implementation to inherit – so no complications – Hence the basis of many “design patterns” What is abstraction? Example: A Priority Queue ADT � Workable answer – a blurring of details � ADT is defined by its interface – what it does � Idea: agree to ignore certain details ( for now ) � Imagine a PriorityQueue with these methods: – Convert original problem to a simpler problem void insert(Comparable item); – Procedural abstraction is one way to simplify – main / * add the item to the queue */ algorithm calls methods to handle detailed steps Comparable remove(); � Works for data types too / * always returns item with highest priority */ – Think ( and write code ) in terms of abstract data types boolean isEmpty(); like Lists, Stacks, Trees, … /* true if queue has no items */ � What should matter – what you can do with a List � Never mind how it works – think about that later � What should not matter – what goes on inside the List – Assume the ADT works – just use it! 1

  2. Interface is enough to use ADT Linked data structures � Easy way to sort – let a priority queue do it � Made up of nodes and links between nodes void easySort(Comparable a[]) { – As purpose is data storage/retrieval, also contains PriorityQueue pq = new PriorityQueue(); information field(s) inside nodes int i, n = a.length; � Simplest is a linear linked list with single links: for (i=0; i<n; i++) // put all items in queue pq.insert(a[i]); – Key is to define a node class to hold info and a link: for (i=n-1; i>=0; i--) // items come out sorted class ListNode { // note: class Entry<E> in Collins text a[i] = pq.remove(); Object data; } // There are more efficient ways to sort, but that’s not the point. ListNode next; � The point is that we can use it without knowing ... /* maybe set and get methods for fields if not nested class */ } how it works. – By convention, next == null if last node in list � Abstraction is good! � Otherwise it refers to next node in the list So what is a linked list, really? List class can hide details � Answer: a sequence of zero or more nodes, with � Interface says nothing about list nodes each node pointing to the next one � Best to prevent clients from direct node access � Need: a reference to the first node – first – Clients don’t have to know nodes even exist! – Often this reference is considered “the list” – Clients cannot set links inappropriately – Might be null – just means it is an empty list � Easiest way (with Java) – private nested class: public class LinkedList { ListNode first; L … private static class ListNode { } } DUS ORD SAN Nested classes/interfaces FYI: more Java nested classes � Okay to define a class (or interface) inside � Local classes another class (or interface) – Defined inside methods or other blocks – Good for grouping logically related types – Not members of the class – local to the block – Nested and outer class share data – even private � Anonymous classes � If declared static – works just like non-nested – When just want an object; no need for type – Can extend, or be extended like any other class – Must extend existing class or implement interface – Can only access static fields/methods of outer class � Purpose is to override one or more methods � If not declared static – called an inner class – Used frequently for event-handling: new ActionListener ( // define anonymous class right here: – Instances of the inner class are associated with an { public void actionPerformed(ActionEvent e) {…} } instance of outer class – the “enclosing object” ); 2

  3. Collection hierarchy (simplified) Map hierarchy (simplified) K, V E <interface>> <interface>> Collection Map E E K, V < <interface>> <interface>> AbstractMap List Set E E AbstractSet AbstractList K, V K, V TreeMap HashMap E E E E TreeSet HashSet ArrayList LinkedList See StudentMap.java (Collins p. 117) See RandomList.java and RandomSet.java (Collins pp. 111, 114) Testing Testing steps � Goal is to find faults � Unit testing – insure each part is correct � Faults (a.k.a. bugs) cause systems to fail – Independently test each function in each file – e.g., a system crashes – the most obvious type of fault � Integration testing – insure parts work together – e.g., a security system that allows unauthorized entry – Test functions working together; not whole system yet – e.g., a shot-down video game plane continues on path � System testing – insure system does what it is � Can verify the presence of bugs, not their absence supposed to do – Testing fails if no bugs are found! (a good thing really) – Lots of testing left to do – especially for large systems � Testing and debugging are separate processes – Includes functional tests, performance tests, acceptance tests, and installation tests – Testing identifies; debugging corrects/removes faults Testing approaches Test plans (i.e., test data contents) � Black box testing – best by independent tester � Test a representative sample of normal cases – Plan good test cases, and conduct automated tests – Usually no way to test all possibilities � But don’t really need to – random sample of cases okay � Open box testing – a separate, preliminary activity – At least be sure to test all normal operations – “Coverage testing” is the goal � Test boundary cases � i.e., test every line of code at least once – Test the extremes – includes empty cases, lone cases, – Includes unit testing and integration testing last case, first case, …, any other “edge” cases � Regression testing – repeat tests frequently � Test error cases too – Because fixing a new bug may re-introduce old ones – e.g., test how bad input is handled – should not crash! – Easy to do with automated testing framework 3

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend