Title: Java / OOP
1Java / OOP
- Inheritance
- Collections/Dynamic arrays
- Simple arrays
- Course repetition
with Kasper B. Graversen!
2Inheritance
- 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.
3Inheritance
- In java we have single source inheritance
- We can inherit from one other class
- We inherit
- Type
- Attributes
- Functionality
4Inheritance
class Vehicle int speed int topspeed
int weight pubblic int drive()
return speed public String
toString() return speed weight
UML Diagram
class Truck extends Vehicle int loadweight
public void load(int load)
loadweight load weight loadweight
public void unload()
loadweight 0 weight - loadweight
Truck tub new Truck() tub.speed
30 tub.weight 2000 System.out.println(tub)
5Inheritance
- 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 work
class CarSeller public boolean buy(Vehicle
car) if(car.topspeed gt 200) public
boolean buyTrucks(Truck truck)
6Inheritance
- In Java all objects (secretly) inherit from class
Object - This explains the magic toString()java.lang.Objec
t - 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.)
7Inheritance Object
- Peeking in the code for toString()Horse h new
Horse()System.out.println(h)givesHorse_at_111f7
1
public String toString() return
getClass().getName() "_at_"
Integer.toHexString(hashCode())
8Collections
- So far weve 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
9Collections
- Instead we need an object which can do the
bookkeeping - gather objects and let us traverse
them
- 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
Pseudo 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)
10Collections
- 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.
11Collections
- 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
12CollectionsVector
- 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()
13CollectionsVector
- 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 -gt we need to type
cast
14Vector in use
- Lets construct a small bookshop
Pseudo 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)
15Vector in use
- Lets 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 lt c.size() i) Book b
(Book) c.get(i)
System.out.print(b)
16Forgetting the typecasting
import java.util.Vector Vector v new
Vector() String s hej v.addElement(s) Strin
g t v.firstElement() incompatible
types found java.lang.Object required
java.lang.String String t v.firstElement()
must be String
t (String) v.firstElement()
17Type 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()
- In class Object there is no walk() method defined
18Collections 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!
19Passing around the vector
- example
class 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 lt horses.size()i)
Horse h (Horse) horses.get(i)
h.walk() public void race(int
rounds) for(int i 0 i lt rounds i)
raceRound() public Vector getHorses()
return horses
class HorseTrader public void
judgeHorses(Vector horses) for(int i 0 i
lt horses.size()i) Horse h (Horse)
horses.get(i)
20Collections and simple types
- 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, Boolean
class RainFallHistogram Vector v new
Vector() public void addRain(double rain)
Double d new Double(rain)
v.add(d)
Short version v.add(new Double(rain))
21Collections 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)
22Arrays
- 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
- Its primitive - we must handle where in the
array inserts are made - Removing is cumbersome
23Arrays
- 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.
24Arrays Creation
- Two ways of making an array
- type arrayid new typesize
- type arrayid val1, val2,
- String countryCodes new String5
- countryCodes is of type String (string array)
25Arrays Accessing
- We now have 5 String slots available (actually 5
pointers of type String). - Accessing happens through
- Further than 4 will yield an IndexOutOfBoundExcept
ion
countryCodes0 DK countryCodes4 new
String(E)
26Arrays drawn
countryCodes0 DK countryCodes4 new
String(E)
27Arrays Accessing
- int lottonumbers 1,34,5,2,20,3,19
- printing the numbers
for(int i 0 i lt lottonumbers.length i)
System.out.print(lottonumbersi)
28Arrays in action...
class HorseRace private int nohorses
private Horse horses HorseRace(int size)
horses new Horsesize nohorses
0 public boolean addHorse(Horse horse)
if(nohorses lt size)
horsesnohorses horse return
true return false
29Arrays Removing elements
- 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
30Arrays Removing elements
- But if the order of the elements in the array
only the second solution can be used. - How to remove elements using method 1
int arr int no // number of elements in
array public void remove(int n) // swap
int tmp arrno arrno arrn
arrn tmp // remove element arrno
null no--
31Multidimensional 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
32Multidimensional arrays
- Making a 2 dim array
- Access to the array must now be made specifying
both dimensions
int table new int34
table00 2
table0 2