CompSci 100E8.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 100E8.2Single inheritance in Javaÿ A class can extend only one class in Java All classes extend Object --- it's the root of the inheritance hierarchy tree Can extend something else (which extends Object), why?ÿ Why do we use inheritance in designing programs/systems? Facilitate code-reuse (what does that mean?) Ability to specialize and change behavioro If I could change how method foo() works, bar() is ok Design methods to call ours, even before we implemento Hollywood principle: don't call us, …CompSci 100E8.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 100E8.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 100E8.5Comparable and Comparatorÿ Both are interfaces, there is no default implementation 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 100E8.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 100E8.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