Transcript Slides 6

Java / OOP
•Inheritance
•Collections/Dynamic arrays
•Simple arrays
•Course repetition
Inheritance
• 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
2
Inheritance
• In java we have single source inheritance
• We can inherit from one other class
• We inherit
– Type
– Attributes
– Functionality
(c) Kasper B. Graversen, 2001
3
class Vehicle
{
int speed;
int topspeed;
int weight;
Inheritance
UML Diagram
Vehicle
speed
topspeed
weight
drive()
toString()
pubblic int drive()
{
return speed;
}
public String toString()
{return ““+speed+“ “+weight;}
}
class Truck extends Vehicle
{
int loadweight;
}
public void load(int load)
{
loadweight = load;
weight += loadweight;
}
public void unload()
{
loadweight = 0;
weight -= loadweight;
}
Truck
loadweight
load()
unload()
Truck tub = new Truck();
tub.speed = 30;
tub.weight = 2000;
System.out.println(tub);
(c) Kasper B. Graversen, 2001
4
Inheritance
• 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 > 200)…}
public boolean buyTrucks(Truck truck)
{…}
}
(c) Kasper B. Graversen, 2001
5
Inheritance
• 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
6
Inheritance: Object
• Peeking in the code for toString()
Horse h = new Horse(…);
System.out.println(h);
gives
Horse@111f71
public String toString()
{
return getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
(c) Kasper B. Graversen, 2001
7
Collections
• 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
8
Collections
• Instead we need an object which can “do
the bookkeeping” - gather objects and let us
traverse them
•We want the collection
Pseudo code
to be able to hold
Collection(); unlimited books
class Bookstore
{ Collection c = new
public void addBook(Book book)
{c.add(book);}
}
public void printStock()
{
for(…all books in c…)
System.out.print(booki)
}
•We want to be able to
easily add and remove
books.
•Then all we need is a
collection for each
(c) Kasper B. Graversen, 2001
category of books 9
Collections
• 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
10
Collections
• 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
11
Collections: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
12
Collections: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
13
Vector in use
• Let’s 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)
}
}
(c) Kasper B. Graversen, 2001
14
Vector 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);}
The typecast
which is only
successful if
stored objects are
of type Book
public void printStock()
{
for(int i = 0; i < c.size(); i++)
{
Book b = (Book) c.get(i);
System.out.print(b);
}
}
}
(c) Kasper B. Graversen, 2001
15
Forgetting the typecasting
import java.util.Vector;
…
Vector v = new Vector();
String s = ”hej”;
v.addElement(s);
String t = v.firstElement();
: incompatible types
found : java.lang.Object
required: java.lang.String
String t = v.firstElement();
^
must be
String t = (String) v.firstElement();
(c) Kasper B. Graversen, 2001
16
Type 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();
horse
h2
Horse
walk()
…
•In class Object there is no walk() method defined
(c) Kasper B. Graversen, 2001
17
Collections: 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
18
Passing
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 < 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
19
Collections 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));
(c) Kasper B. Graversen, 2001
20
Collections 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
21
Arrays
• 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
22
Arrays
• 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
23
Arrays: 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)
01234
countryCodes
(c) Kasper B. Graversen, 2001
24
Arrays: Accessing
• We now have 5 String slots available (actually
5 pointers of type String).
• Accessing happens through []
countryCodes[0] = “DK”;
…
countryCodes[4] = new String(“E”);
• Further than 4 will yield an
IndexOutOfBoundException
(c) Kasper B. Graversen, 2001
25
Arrays drawn
countryCodes[0] = “DK”;
…
countryCodes[4] = new String(“E”);
01234
countryCodes
“DK”
“E”
(c) Kasper B. Graversen, 2001
26
Arrays: 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
27
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
28
Arrays: 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
(c) Kasper B. Graversen, 2001
29
Arrays: 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 = arr[no];
arr[no] = arr[n];
arr[n] = tmp;
// remove element
arr[no]= null;
no--;
}
(c) Kasper B. Graversen, 2001
30
Multidimensional 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
31
Multidimensional arrays
• Making a 2 dim array
int[][] table = new int[3][4];
• Access to the array must now be made
specifying both dimensions
table[0][0] = 2;
table[0] = 2;
(c) Kasper B. Graversen, 2001
32