Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 240 times |
Download: | 2 times |
Java / OOPJava / OOP•Inheritance•Collections/Dynamic arrays•Simple arrays•Course repetition
(c) Kasper B. Graversen, 2001 2
InheritanceInheritance
• In nature we constantly find inheritance
• We have different races which originates from some common source
• Horse– Iceland pony– Arabian– Zebra
• They have common features physically or mentally.
(c) Kasper B. Graversen, 2001 3
InheritanceInheritance
• In java we have single source inheritance
• We can inherit from one other class
• We inherit– Type– Attributes– Functionality
(c) Kasper B. Graversen, 2001 4
class Truck extends Vehicle{ int loadweight;
public void load(int load) { loadweight = load; weight += loadweight; } public void unload() { loadweight = 0; weight -= loadweight;} }
InheritanceInheritanceclass Vehicle { int speed; int topspeed; int weight;
pubblic int drive() { return speed; } public String toString() {return ““+speed+“ “+weight;}}
Truck tub = new Truck();tub.speed = 30;tub.weight = 2000;System.out.println(tub);
Vehiclespeedtopspeedweightdrive()toString()
Truckloadweightload()unload()
UML Diagram
(c) Kasper B. Graversen, 2001 5
InheritanceInheritance• A Truck is a Truck and a Vehicle (it
has all methods and attributes inherited from Vehicle)
• Since a Truck is both types this will workclass CarSeller{ public boolean buy(Vehicle car) {…if(car.topspeed > 200)…}
public boolean buyTrucks(Truck truck) {…}}
(c) Kasper B. Graversen, 2001 6
InheritanceInheritance
• In Java all objects (secretly) inherit from class Object
• This explains the magic toString()java.lang.Object
• From this we can deduct that all objects are of type Object
• And that the pointer Object p can point to any object (Horses, books etc.)
(c) Kasper B. Graversen, 2001 7
Inheritance: ObjectInheritance: Object
• Peeking in the code for toString()
Horse h = new Horse(…);System.out.println(h);givesHorse@111f71
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode());}
(c) Kasper B. Graversen, 2001 8
CollectionsCollections
• So far we’ve missed out on collections. We have had a hard time defining several horses for out horserace or for our bookstore.
• Automatic traversal was made impossible
class Bookstore{ Book kids1, kids2,kids3; Book chem1,chem2;}
(c) Kasper B. Graversen, 2001 9
CollectionsCollections• Instead we need an object which can “do
the bookkeeping” - gather objects and let us traverse them
Pseudo codeclass Bookstore{ Collection c = new Collection(); public void addBook(Book book) {c.add(book);}
public void printStock() { for(…all books in c…) System.out.print(booki)} }
•We want the collection to be able to hold unlimited books
•We want to be able to easily add and remove books.
•Then all we need is a collection for each category of books
(c) Kasper B. Graversen, 2001 10
CollectionsCollections• Java has made some collections classes for
us. But instead of handling specific classes such as Books or HorseRaces they operate on Objects
• As all objects are of type Object all classes can use the collections
• However, specific traversal, search etc. must be handled by us, and sometimes at the cost of efficiency.
(c) Kasper B. Graversen, 2001 11
CollectionsCollections
• There are a lot of collections in Java, all with their advantages and drawbacks.
• Their interface are all alike so to you the difference is of no concern (yet)
• Names– Vector– ArrayList– LinkedList
(c) Kasper B. Graversen, 2001 12
Collections:VectorCollections:Vector
• We use Vector since the book uses it
• Its old and some methods should not be used due to a later naming conventions in the collections– The javadoc java.util.Vector– Standard methods in all collections: add(), get(), remove(), size(), isEmpty()
(c) Kasper B. Graversen, 2001 13
Collections:VectorCollections:Vector
• Notably– boolean add(Object o)
– Object get(int index)
– We can insert (add) any object
– When we retrieve from the collection we get objects referenced as Object -> we need to type cast
(c) Kasper B. Graversen, 2001 14
Vector in useVector in use
• Let’s construct a small bookshopPseudo code class Bookstore{ Collection c = new Collection(); public void addBook(Book book) { c.add(book); }
public void printStock() { for(…all books in c…) System.out.print(booki) } }
(c) Kasper B. Graversen, 2001 15
Vector in useVector in use• Let’s construct a small bookshop
import java.util.*;class BookStore { Vector c = new Vector(); public void addBook(Book book) {c.add(book);}
public void printStock() { for(int i = 0; i < c.size(); i++) { Book b = (Book) c.get(i); System.out.print(b); } } }
The typecast which is only successful if stored objects are of type Book
(c) Kasper B. Graversen, 2001 16
Forgetting the typecastingForgetting the typecastingimport java.util.Vector;…Vector v = new Vector();String s = ”hej”;v.addElement(s);String t = v.firstElement();
: incompatible typesfound : java.lang.Objectrequired: java.lang.String
String t = v.firstElement(); ^must beString t = (String) v.firstElement();
(c) Kasper B. Graversen, 2001 17
Type casting objectsType casting objects
• Typecasting objects does not change the values of the objects.
• Casting decides which attributes/methods are available
Horse horse = new Horse(…);horse.walk();Object h2 = (Object) horse;h2.walk();
Horsewalk()…
horse
h2
•In class Object there is no walk() method defined
(c) Kasper B. Graversen, 2001 18
Collections: ObservationsCollections: Observations
• We see the collection of objects is itself just an object.
• This object can be passed around - like any other object
• Notice you pass a pointer - so changing the vector yields change in the rest of the program!
(c) Kasper B. Graversen, 2001 19
Passing around the vectorPassing around the vector- example- exampleclass Horse{ name, energy…}
class HorseRace{ private Vector horses = new Vector(); public void addHorse(Horse h){horses.add(h);} private void raceRound() { for(int i = 0; i < horses.size();i++) { Horse h = (Horse) horses.get(i); h.walk(); } } public void race(int rounds) { for(int i = 0; i < rounds; i++) raceRound(); } public Vector getHorses(){ return horses;}} class HorseTrader{ public void judgeHorses(Vector horses) { for(int i = 0; i < horses.size();i++) { Horse h = (Horse) horses.get(i);
…
(c) Kasper B. Graversen, 2001 20
Collections and simple Collections and simple typestypes
• Simple types are not supported. why? Simple types are not objects, hence are not of type Object
• Solution: Use wrapper classes Integer, Long Float, Double, Booleanclass RainFallHistogram{ Vector v = new Vector(); public void addRain(double rain) { Double d = new Double(rain); v.add(d); }}
Short versionv.add(new Double(rain));
(c) Kasper B. Graversen, 2001 21
Collections summaryCollections summary
• Good example of code-reuse
• Collections can support fast searching while the interface (add/get) is unchanged
• Cumbersome (casting)
• Can contain more than one type at a time
• No support for simple types
• Slow (casting and method calls)
(c) Kasper B. Graversen, 2001 22
ArraysArrays• Operate on all types including simple types
• No casting required
• Only one type can reside in arrays (including subtypes of course)
• Much faster
• Size is fixed
• It’s primitive - we must handle where in the array inserts are made
• Removing is cumbersome
(c) Kasper B. Graversen, 2001 23
ArraysArrays• An array is a variable which is able to hold
more than one value
• We access the values using []• We can ask for the size of the array
with .length (not the number of element in the array!)
• Empty slots has the value null• Arrays are usually called “syntactic sugar”
since it adds nothing new to the language.
(c) Kasper B. Graversen, 2001 24
Arrays: CreationArrays: Creation• Two ways of making an array
– type[] arrayid = new type[size];– type[] arrayid = {val1, val2,…};
String[] countryCodes = new String[5];
• countryCodes is of type String[] (string array)
countryCodes
01234
(c) Kasper B. Graversen, 2001 25
Arrays: AccessingArrays: Accessing
• We now have 5 String slots available (actually 5 pointers of type String).
• Accessing happens through []
• Further than 4 will yield an IndexOutOfBoundException
countryCodes[0] = “DK”;…countryCodes[4] = new String(“E”);
(c) Kasper B. Graversen, 2001 26
Arrays drawnArrays drawn
countryCodes[0] = “DK”;…countryCodes[4] = new String(“E”);
countryCodes
01234
“DK” “E”
(c) Kasper B. Graversen, 2001 27
Arrays: AccessingArrays: Accessing
• int[] lottonumbers = {1,34,5,2,20,3,19};
• printing the numbers
for(int i = 0; i < lottonumbers.length; i++) System.out.print(lottonumbers[i]);
(c) Kasper B. Graversen, 2001 28
Arrays in action...Arrays in action...• The HorseRace rewritten
class HorseRace{ private int nohorses; private Horse[] horses;
HorseRace(int size) { horses = new Horse[size]; nohorses = 0; }
public boolean addHorse(Horse horse) { if(nohorses < size) { horses[nohorses++] = horse; return true; } return false; } }
(c) Kasper B. Graversen, 2001 29
Arrays: Removing Arrays: Removing elementselements• Since arrays are simpler we can choose between
several models– Swap with end element and remove end element– Remove element and move all other elements– Just remove element (requires a more costly insert)
• The first two solutions wants the array to be completely filled from left
• The last one allows “holes” in the array
(c) Kasper B. Graversen, 2001 30
Arrays: Removing Arrays: Removing elementselements
• But if the order of the elements in the array only the second solution can be used.
• How to remove elements using method 1int arr[];int no; // number of elements in array… public void remove(int n){ // swap int tmp = arr[no]; arr[no] = arr[n]; arr[n] = tmp; // remove element arr[no]= null; no--;}
(c) Kasper B. Graversen, 2001 31
Multidimensional arraysMultidimensional arrays
• Arrays easily support multidimensional data• 2 dim. “mm rain” on “y-axis” and location on “x-axis”• 3 dim. The third axis is the date • Limitations
– The axis must be of the same type– each row or column have the same number of slots
(c) Kasper B. Graversen, 2001 32
Multidimensional arraysMultidimensional arrays• Making a 2 dim array
• Access to the array must now be made specifying both dimensions
int[][] table = new int[3][4];
table[0][0] = 2; table[0] = 2;