Download Method Summary - Karlstads universitet

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1 (13)
Karlstads universitet
Institutionen för Informationsteknologi
Datavetenskap
Tentamen i Objektorienterad programmering med Java, DAVA15 ( 15p )
Tisdag 04-06-01 kl. 08.15 – 13.15
Ansvarig lärare:
Hjälpmedel:
Poäng:
Åsalena Warnqvist
Inga
Max 60p, betyg 5 – 50p, betyg 4 – 40p, betyg 3 – 30p
(varav minimum 20p från tentamen och 10p från labbarna)
Tentamen:
Labbarna:
Max 40p, betyg 5 – 34p, betyg 4 – 27p, betyg 3 – 20p
Max 20p, betyg 5 – 18p, betyg 4 – 14p, betyg 3 – 10p
Skriv tydligt – läs frågorna noggrant – använd gärna figurer
Även delvis lösta uppgifter kan ge poäng, lämna därför in dessa!
Lycka till!
Uppgift 1: Begrepp (5 poäng)
Förklara följande begrepp kortfattat:
a) Coupling
b) Cohesion
c) Override (omdefiniera)
d) Overload (överlagra)
e) Design patterns (designmönster)
(1 p)
(1 p)
(1 p)
(1 p)
(1 p)
Uppgift 2: Samlingar (5 poäng)
Nedanstående kod kommer från projektet Notebook i kapitel 4 i kursboken. I första versionen
används en ArrayList och i den andra versionen används en array (”fixed-size collection”)
istället.
a) Förklara skillnaden mellan de båda samlingarna. Ange för och nackdelar med respektive
lösning.
(3 p)
/*----- Version 1 -------------------------------------------*/
import java.util.ArrayList;
public class Notebook
{
// Storage for an arbitrary number of notes.
2 (13)
private ArrayList notes;
/**
* Perform any initialization that is required for the
* notebook.
*/
public Notebook()
{
notes = new ArrayList();
}
/*---- Version 2 --------------------------------------------*/
public class Notebook
{
// Storage for an arbitrary number of notes.
private String[] notes;
/**
* Perform any initialization that is required for the
* notebook.
*/
public Notebook()
{
notes = new String[100];
}
b) I versionen med ArrayList finns följande metod. Skriv om metoden så att den kan gå
igenom listan med noteringar med hjälp av en iterator istället. (Du har tillgång till Javas API
för ArrayList och Iterator i bilaga A)
(2 p)
/**
* List all notes in the notebook.
*/
public void listNotes()
{
int index = 0;
while(index < notes.size()) {
System.out.println(notes.get(index));
index++;
}
}
Uppgift 3: Arv och polymorfism (5 poäng)
I bilaga B finns kod för ett program som lagrar information om CD och videofilmer. En
testklass ( DBUI.java ) lägger in 8 föremål och skriver ut dessa.
a) Vad skrivs ut när programmet körs?
(1 p)
b) Förklara, med hjälp av kodexemplet och dina kunskaper från kursboken, begreppen
method lookup (3p) och method polymorphism (1p).
(3+1 p)
3 (13)
Uppgift 4: Gränssnitt, abstrakta klasser och designmönster (15 poäng)
Ovanstående exempel är ett klassdiagram för designmönstret Decorator. Med hjälp av dina
kunskaper från kursboken och diagrammet, svara på följande:
a) Förklara utifrån exemplet vad Decorator-mönstret gör. Ta gärna hjälp av figurer i din
beskrivning.
(7 p)
b) Klassen Decorator i exemplet är abstrakt, medan VisualComponent är ett gränssnitt. Vilka
skillnader och likheter finns det mellan abstrakta klasser och gränssnitt (om det finns
några)? Vilka är deras respektive uppgifter?
(4 p)
c) I Java är det inte tillåtet med multipelt arv. Hur har man löst det i Java istället och vilka
fördelar och nackdelar finns det med Javas lösning?
(4 p)
Uppgift 5: Undantag (5 poäng)
a) I Java används två typer av undantag, kontrollerade (checked exceptions) och
okontrollerade (unchecked exceptions).
Förklara skillnaden mellan dessa två.
(2 p)
b) När och hur anser du att undantag ska användas tillsammans med kontrakt? Motivera dina
svar.
(3 p)
Uppgift 6: Objektorientering (5 poäng)
Vad anser du vara de viktigaste principerna i objektorienterad programmering, förutom arv
och polymorfism? Motivera dina svar.
4 (13)
Bilaga A
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS
FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD
All Classes
JavaTM 2 Platform
Std. Ed. v1.4.2
java.util
Class ArrayList
java.lang.Object
java.util.AbstractCollection
java.util.AbstractList
java.util.ArrayList
All Implemented Interfaces:
Cloneable, Collection, List, RandomAccess, Serializable
public class ArrayList
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all
elements, including null. In addition to implementing the List interface, this class provides methods to
manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector,
except that it is unsynchronized.)
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in
amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear
time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list.
It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows
automatically. The details of the growth policy are not specified beyond the fact that adding an element has
constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements
using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance
concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A
structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the
backing array; merely setting the value of an element is not a structural modification.) This is typically
accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the
list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to
prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(...));
The iterators returned by this class's iterator and listIterator methods are fail-fast: if list is structurally modified at
any time after the iterator is created, in any way except through the iterator's own remove or add methods, the
iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator
fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the
future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to
make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw
ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that
depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect
bugs.
This class is a member of the Java Collections Framework.
Since:
1.2
See Also:
Collection, List, LinkedList, Vector, Collections.synchronizedList(List),
Serialized Form
5 (13)
Field Summary
Fields inherited from class java.util.AbstractList
modCount
Constructor Summary
ArrayList()
Constructs an empty list with an initial capacity of ten.
ArrayList(Collection c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the
collection's iterator.
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
Method Summary
void add(int index, Object element)
Inserts the specified element at the specified position in this list.
boolean add(Object o)
Appends the specified element to the end of this list.
boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this list, in the order
that they are returned by the specified Collection's Iterator.
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified Collection into this list, starting at the specified
position.
void clear()
Removes all of the elements from this list.
Object clone()
Returns a shallow copy of this ArrayList instance.
boolean contains(Object elem)
Returns true if this list contains the specified element.
void ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at
least the number of elements specified by the minimum capacity argument.
Object get(int index)
Returns the element at the specified position in this list.
int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality using the equals
method.
boolean isEmpty()
Tests if this list has no elements.
int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object in this list.
Object remove(int index)
Removes the element at the specified position in this list.
6 (13)
protected removeRange(int fromIndex, int toIndex)
void
Removes from this List all of the elements whose index is between fromIndex, inclusive
and toIndex, exclusive.
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element.
int size()
Returns the number of elements in this list.
Object[] toArray()
Returns an array containing all of the elements in this list in the correct order.
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the runtime
type of the returned array is that of the specified array.
void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
Methods inherited from class java.util.AbstractList
equals, hashCode, iterator, listIterator, listIterator, subList
Methods inherited from class java.util.AbstractCollection
containsAll, remove, removeAll, retainAll, toString
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.List
containsAll, equals, hashCode, iterator, listIterator, listIterator,
remove, removeAll, retainAll, subList
7 (13)
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS
FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD
All Classes
JavaTM 2 Platform
Std. Ed. v1.4.2
java.util
Interface Iterator
All Known Subinterfaces:
ListIterator
All Known Implementing Classes:
BeanContextSupport.BCSIterator
public interface Iterator
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators
differ from enumerations in two ways:
•
Iterators allow the caller to remove elements from the underlying collection during the iteration with
well-defined semantics.
•
Method names have been improved.
This interface is a member of the Java Collections Framework.
Since:
1.2
See Also:
Collection, ListIterator, Enumeration
Method Summary
boolean hasNext()
Returns true if the iteration has more elements.
Object next()
Returns the next element in the iteration.
void remove()
Removes from the underlying collection the last element returned by the iterator (optional
operation).
8 (13)
Bilaga B
public class DBUI{
private Database db;
public DBUI(){
db = new Database();
}
public void fillDB(){
//public Video(String theTitle, String theDirector, int time)
Video v1 = new Video("minFilm", "Anna Andersson", 123);
Video v2 = new Video("dinFilm", "Peter Peterson", 345);
Video v3 = new Video("hansFilm", "Per Persson", 122);
Video v4 = new Video("hennesFilm", "Karin Kall", 321);
//public CD(String theTitle, String theArtist, int tracks,
int time)
CD
CD
CD
CD
cd1
cd2
cd3
cd4
=
=
=
=
new
new
new
new
CD("minCD", "diLeva", 15, 155);
CD("dinCD" , "Metallica", 4, 23);
CD("hansCD", "Perssons Pack", 12, 92);
CD("hennesCD", "Kalle Baah", 22, 123);
db.addItem(v1);
db.addItem(v2);
db.addItem(v3);
db.addItem(v4);
db.addItem(cd1);
db.addItem(cd2);
db.addItem(cd3);
db.addItem(cd4);
}
public void skrivUt(){
db.list();
}
public static void main(String[] argv){
DBUI ui = new DBUI();
ui.fillDB();
ui.skrivUt();
}
}
9 (13)
/**
* The Item class represents a multi-media item.
* Information about the item is stored and can be retrieved.
* This class serves as a superclass for more specific itms.
*
* @author Michael Kolling and David J. Barnes
* @version 2002-05-06
*/
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
/**
* Initialise the fields of the item.
*/
public Item(String theTitle, int time)
{
title = theTitle;
playingTime = time;
gotIt = false;
comment = "<no comment>";
}
/**
* Enter a comment for this item.
*/
public void setComment(String comment)
{
this.comment = comment;
}
/**
* Return the comment for this item.
*/
public String getComment()
{
return comment;
}
/**
* Set the flag indicating whether we own this item.
*/
public void setOwn(boolean ownIt)
{
gotIt = ownIt;
}
/**
* Return information whether we own a copy of this item.
*/
public boolean getOwn()
{
return gotIt;
}
/**
* Print details of this item to the text terminal.
*/
10 (13)
public void print()
{
System.out.print(title + " (" + playingTime + " mins)");
if(gotIt) {
System.out.println("*");
} else {
System.out.println();
}
System.out.println("
" + comment);
}
}
11 (13)
/**
* The Video class represents a video object. Information about the
* video is stored and can be retrieved.
*
* @author Michael Kolling and David J. Barnes
* @version 2002-05-06
*/
public class Video extends Item
{
private String director;
/**
* Constructor for objects of class Video
*/
public Video(String theTitle, String theDirector, int time)
{
super(theTitle, time);
director = theDirector;
}
/**
* Return the director for this video.
*/
public String getDirector()
{
return director;
}
/**
* Print details of this video to the text terminal.
*/
public void print()
{
System.out.println("
director: " + director);
}
}
12 (13)
/**
* The CD class represents a CD object. Information about the CD is stored
and
* can be retrieved.
* @author Michael Kolling and David J. Barnes
* @version 2002-05-06
*/
public class CD extends Item
{
private String artist;
private int numberOfTracks;
/**
* Constructor for objects of class CD
*/
public CD(String theTitle, String theArtist, int tracks, int time)
{
super(theTitle, time);
artist = theArtist;
numberOfTracks = tracks;
}
/**
* Return the artist for this CD.
*/
public String getArtist()
{
return artist;
}
/**
* Return the number of tracks on this CD.
*/
public int getNumberOfTracks()
{
return numberOfTracks;
}
/**
* Print details of this CD to the text terminal.
*/
public void print()
{
System.out.println("
" + artist);
System.out.println("
tracks: " + numberOfTracks);
}
}
13 (13)
import java.util.ArrayList;
import java.util.Iterator;
import java.lang.*;
/**
* The database class provides a facility to store CD and video
* objects. A list of all CDs and videos can be printed to the
* terminal.
*
* This version does not save the data to disk, and it does not
* provide any search functions.
*
* @author Michael Kolling and David J. Barnes
* @version 2002-05-06
*
* @version 2004-05-25
* slightly modified to suit the exam
*/
public class Database
{
private ArrayList items;
/**
* Construct an empty Database.
*/
public Database()
{
items = new ArrayList();
}
/**
* Add an item to the database.
*/
public void addItem(Item theItem)
{
items.add(theItem);
}
/**
* Print a list of all currently stored CDs and videos to the
* text terminal.
*/
public void list()
{
int index = 0;
while(index<items.size()) {
Item it = (Item)items.get(index);
it.print();
index++;
}
}
}