CompSci 100E7.1Inheritance and Interfacesÿ Inheritance models an "is-a" relationshipþ A dog is a mammal, an ArrayList is a List, a square is a shape, …ÿ Write general programs to understand the abstraction,advantages?void doShape(Shape s) {System.out.println(s.area());System.out.println(s.perimeter());s.expand(2.0);}ÿ But a dog is also a quadruped, how can we deal with this?CompSci 100E7.2Single inheritance in Javaÿ A class can extend only one class in Javaþ All classes extend Object --- it's the root of the inheritancehierarchy treeþ Can extend something else (which extends Object), why?ÿ Why do we use inheritance in designingprograms/systems?þ Facilitate code-reuse (what does that mean?)þ Ability to specialize and change behavioro If I could change how method foo() works, bar() isokþ Design methods to call ours, even before we implemento Hollywood principle: don't call us, …CompSci 100E7.3Multiple Interfacesÿ Classes (and interfaces) can implement multiple interfacesþ A dog is a mammal, a quadruped, a petþ How come canine is different?þ What behavior do quadrupeds have? Pets have?ÿ An interface specifies the name (and signature) of methodsþ No implementation, no state/fieldsþ Yes for constantsÿ In this course, by convention, we'll often use interfacesþ Emphasize design before implementationþ Use abstract/default classes for code reuse, stateCompSci 100E7.4Inheritance Examplepublic class UtilRecord extends Record {// assumes Record’s fields are protected, not privateprivate String kind;public UtilRecord(){this("", "", 0, 0, "", "");}public UtilRecord(String a, String f, int s, int o,String e, String k) {super(a,f,s,o,e);kind = k;}/* etc */CompSci 100E7.5Comparable and Comparatorÿ Both are interfaces, there is no defaultimplementationþ Contrast with .equals(), default implementation?þ Contrast with .toString(), default?ÿ Where do we define a Comparator?þ In its own .java file, nothing wrong with thatþ Private, used for implementation and not public behavioro Use a nested class, then decide on static or non-statico Non-static is part of an object, access inner fieldsÿ How do we use the Comparator?þ Sort, Sets, Maps (in the future)ÿ Does Hashing (future topic) have similar problems?CompSci 100E7.6Comparable Examplepublic class Record implements Comparable {public Record(String a, String f, int s, int o,String e) {...}public Record(Record rec) {...}int compareTo(Record r) {// comparision code goes here//setntoneg#if<,0if==,andpos#if>return n}CompSci 100E7.7MVC: Model, View, Controllerÿ A model is the state and brains of a systemþ In a game it's all the pieces and where they areþ In a spreadsheet it's the data and the formulaeÿ The view is how we look at the modelþ Spread sheet has graphs, charts, cells, text, …þ Game has board, number of opponents, hit-points, …ÿ When the model changes, the views reflect the changesþ The model tells the views how/if it has changedþ Model sends information to views ORþ View asks model for
View Full Document