Studiekompasset.dkKlasse: Universitet el. Videregående 3. år · Fag: Andet
Noter til
Universitet el. Videregående 3. år
Side 1 af 124
KAPITEL 1 KLASSER OG OBJEKTER ....................................................................................... 5
OBJEKT MODEL ................................................................................................................................ 5
KLASSE BEGREBET ............................................................................................................................ 5
KLASSER OG OBJEKTER ..................................................................................................................... 6
SKABELSE AF OBJEKTER .................................................................................................................... 7
NEW OPERATOREN ............................................................................................................................ 7
NULL REFERENCEN .......................................................................................................................... 8
TILDELING AF OBJEKT REFERENCE .................................................................................................... 9
DEFINERING AF EN KLASSE ............................................................................................................. 10
METODE OG VARIABLE MODIFIERS .................................................................................................. 11
CLASS MODIFIERS ........................................................................................................................... 11
I
NSTANSE VARIABLER ..................................................................................................................... 12
D
EFINERING AF INSTANSE METODER .............................................................................................. 12
INDKAPSLING .................................................................................................................................. 13
CONSTRUCTORS .............................................................................................................................. 14
DEFINERING AF CONSTRUCTORS ..................................................................................................... 15
THIS-REFERENCEN ......................................................................................................................... 15
OVERLOADING ................................................................................................................................ 16
VÆRDIOVERFØRSEL TIL METODER .................................................................................................. 17
OVERRSEL AF REFERENCER TIL METODER ................................................................................... 18
OVERLOADING CONSTRUCTORS ...................................................................................................... 19
SAMMENHÆNG MELLEM CONSTRUCTORS ....................................................................................... 20
KLASSE VARIABLER (STATIC) .......................................................................................................... 20
KLASSE METODER (STATIC) ............................................................................................................ 21
KLASSE METODER <> INSTANCE METODER ..................................................................................... 21
EXEMPLER I KLASSE OG INSTANS METODER .................................................................................... 22
FINAL VARIABLER ........................................................................................................................... 23
EKSEMPLER KLASSER OG OBJEKTER ............................................................................................... 24
Class Person .............................................................................................................................. 24
KAPITEL 2 SUBKLASSER OG ARV ......................................................................................... 26
ARV ................................................................................................................................................ 26
ARVE HIRAKI ................................................................................................................................... 27
EXTENDS ......................................................................................................................................... 27
SEMANTIK AF ARV .......................................................................................................................... 28
SUBKLASSENS CONSTRUCTOR ......................................................................................................... 28
OVERRIDING ................................................................................................................................... 29
KALD AF SUPERKLASSENS SKJULTE METODER ................................................................................ 30
ADGANG TIL VARIABLER OG METODER ........................................................................................... 30
UDSKIFTNING AF OBJEKT REFERENCER .......................................................................................... 31
POLYMORPHISME ............................................................................................................................ 32
STÆRK TYPE KONTROL .................................................................................................................... 32
FINAL .............................................................................................................................................. 33
OBJECT KLASSEN ............................................................................................................................ 34
DESIGN (IS A) ................................................................................................................................... 35
DESIGN FOR UDVIDELSER ................................................................................................................ 35
EKSEMPLER PÅ ARV ........................................................................................................................ 36
Noter til
Side 2 af 124
Class Ansat ................................................................................................................................. 36
KAPITEL 3 ABSTRAKTE KLASSER OG INTERFACES ....................................................... 38
ABSTRAKTE KLASSER...................................................................................................................... 39
ABSTRAKTE METODER .................................................................................................................... 40
POLYMORFI MED ABSTRAKTE KLASSER ........................................................................................... 40
INTERFACES .................................................................................................................................... 41
DEFINERING AF ET INTERFACE ........................................................................................................ 41
IMPLEMENTERING AF ET INTERFACE ............................................................................................... 42
POLYMORFI ..................................................................................................................................... 43
EKSEMPLERINTERFACES ............................................................................................................ 43
Eksempel Bobblesort .................................................................................................................. 44
Eksempel Interface Lookup ........................................................................................................ 45
KAPITEL 4 STRING KLASSEN ................................................................................................... 47
U
DVALGTE STRING METODER ......................................................................................................... 48
TOSTRING() METODEN ..................................................................................................................... 49
STRINGBUFFER KLASSEN ................................................................................................................ 49
WRAPPER KLASSER ......................................................................................................................... 50
STRING KONVERTERING .................................................................................................................. 50
EKSEMPLER ..................................................................................................................................... 51
KAPITEL 5 EXCEPTIONS ............................................................................................................ 52
FEJLBEHANDLING VHA. EXCEPTIONS ............................................................................................... 53
JAVA OG EXCEPTIONS ...................................................................................................................... 53
SIMPELT EKSEMPELTRY OG CATCH .............................................................................................. 54
THROWABLE ................................................................................................................................... 54
EKSEMPLER PÅ FEJL ........................................................................................................................ 55
OPSAMLING AF EXCEPTIONS (CATCH) ............................................................................................. 55
FINALLY .......................................................................................................................................... 56
ET SAMLET EKSEMPEL ..................................................................................................................... 56
ERKLÆREDE EXCEPTIONS ................................................................................................................ 57
PASSING THE BUCK ......................................................................................................................... 58
BEHANDLING AF EXCEPTION I KALDTE METODER ............................................................................ 58
EXCEPTIONS OG OVERRIDING .......................................................................................................... 59
BRUGER DEFINEREDE EXCEPTIONS .................................................................................................. 60
THROWING EXCEPTIONS ................................................................................................................. 60
INFORMATION OM EXCEPTIONS ....................................................................................................... 61
STØRRE EKSEMPLER ........................................................................................................................ 61
Eksempel på exceptions ............................................................................................................. 62
KAPITEL 6 PACKAGES ............................................................................................................... 64
PACKAGE OPBYGNING ..................................................................................................................... 64
REFERERING TIL KLASSER I EN PACKAGE ........................................................................................ 65
IMPORTERING AF KLASSER .............................................................................................................. 66
PLACERING AF PACKAGE ................................................................................................................. 66
SPECIFICERING AF EN KLASSES PACKAGE ........................................................................................ 67
ACCESS REGLER FOR PACKAGE, KLASSER OG INTERFACE ................................................................ 68
Noter til
Side 3 af 124
KAPITEL 7 GARBAGE COLLECTION ..................................................................................... 69
FINALIZE() METODEN ..................................................................................................................... 69
KAPITEL 8 APPLETS .................................................................................................................... 71
APPLICATIONER <> APPLETS .......................................................................................................... 71
HVORDAN AFVIKLES EN APPLET ..................................................................................................... 71
APPLET KLASSEN ............................................................................................................................ 72
EN APPLETS LIVSCYKLUS ................................................................................................................ 73
SKRIV EN SIMPEL APPLET ................................................................................................................ 74
AFVIKLING AF EN APPLET ............................................................................................................... 74
OVERFØR PARAMETER TIL EN APPLET ............................................................................................. 75
GRAPHICS KLASSEN ........................................................................................................................ 76
TEGNE TEKST .................................................................................................................................. 77
ÆNDRING AF FONTEN ..................................................................................................................... 77
ÆNDRING AF FARVE ........................................................................................................................ 78
TEGNING AF LINIER OG FORMER ...................................................................................................... 79
SIKKERHED VED APPLETS ............................................................................................................... 80
EKSEMPLER ..................................................................................................................................... 81
Eksempel Applet_Spot ................................................................................................................ 81
KAPITEL 9 KOMPONENTER I JAVA-UI ................................................................................. 85
OVERBLIK OVER KOMPONENTER I JAVA-UI .................................................................................. 85
AWT KOMPONENTER ...................................................................................................................... 86
LABEL OG BUTTON ......................................................................................................................... 87
TEKST INPUT ................................................................................................................................... 88
KOMPONENTER TIL BRUGER VALG .................................................................................................. 88
EVENT MODEL ................................................................................................................................ 89
EVENTS ........................................................................................................................................... 90
AWT EVENTS OG DERES KILDE ....................................................................................................... 91
AWT EVENT-LISTENER INTERFACES .............................................................................................. 92
REGISTRERING AF EN EVENT-LISTENER .......................................................................................... 92
EVENT NOTIFICERING ..................................................................................................................... 93
ET SIMPELT EKSEMPEL .................................................................................................................... 94
FLERE AWT EVENTS ...................................................................................................................... 95
EN MOUSE OG ITEM LISTENER ........................................................................................................ 96
BEHANDLING AF EVENTS ................................................................................................................ 97
FIRE MÅDER AT IMPLEMENTERE LISTENER INTERFACE ................................................................... 97
STANDARD ADAPTER KLASSER ....................................................................................................... 98
EKSEMPEL PÅ EVENTHÅNDTERING I EN ANONYM KLASSE ............................................................... 99
EKSEMPLER ................................................................................................................................... 100
CONTAINERS ................................................................................................................................. 101
LAYOUT HÅNDTERING ................................................................................................................... 102
FLOWLAYOUT ............................................................................................................................... 103
BORDERLAYOUT ........................................................................................................................... 103
GRIDLAYOUT ................................................................................................................................ 104
BRUG PANELS TIL AT FORBEDRE LAYOUTET ................................................................................. 105
KAPITEL 11 OBSERVER OG OBSERVABLE ........................................................................ 106
Noter til
Side 4 af 124
DESIGN PATTERN .......................................................................................................................... 106
PROBLEM ...................................................................................................................................... 107
EKSEMPEL PÅ OBSERVER OG OBSERVABLE .................................................................................. 107
IMPLEMENTERING ......................................................................................................................... 108
EKSEMPLER ................................................................................................................................... 108
Eksempel på Observer og Observable ..................................................................................... 109
KAPITEL 12 COLLECTION FRAMEWORK .......................................................................... 112
FORDELE VED COLLECTION .......................................................................................................... 112
SAMMENHÆNGEN MELLEM INTERFACES I COLLECTION ................................................................ 113
BESKRIVELSE AF DE FORSKELLIGE INTERFACES ............................................................................ 113
FORMÅLET MED INTERFACE COLLECTION(ABSTRAKT) ................................................................. 114
METODER I COLLECTION INTERFACE ............................................................................................ 114
METODER OG EKSEMPEL PÅ ITERATOR INTERFACE ....................................................................... 115
METODER I LIST INTERFACE ......................................................................................................... 115
OPLYSNINGER OM LIST INTERFACE ............................................................................................... 116
METODER I LISTITERATOR INTERFACE ......................................................................................... 116
HVOR ER INTERFACENE IMPLEMENTERET ..................................................................................... 117
VALG AF IMPLEMENTERING .......................................................................................................... 117
ALGORITMER FRA KLASSEN COLLECTIONS ................................................................................... 118
UDDRAG AF METODER I COLLECTIONS ......................................................................................... 118
SOTERINGS ORDEN (COMPARABLE/COMPERATOR) ....................................................................... 119
KAPITEL 13 STREAMS OG IO ................................................................................................. 120
FIL KLASSEN ................................................................................................................................. 120
FILE I/O STREAMS......................................................................................................................... 120
EKSEMPEL PÅ BRUG AF STREAMS .................................................................................................. 121
FileInputStream ....................................................................................................................... 121
FileOutputStream ..................................................................................................................... 121
INDEKS .......................................................................................................................................... 123
Noter til
Side 5 af 124
Kapitel 1 Klasser og Objekter
Objekt Model
Object orientation is all about modelling real world objects or concepts in software. Java is an ideal
language for doing this. In fact, unlike some languages like C and C++, it forces you to think in an
object-oriented way, since every piece of Java code must be contained within a class definition.
Most of the examples we will use are based around a car. In the real world, we create a design for a
car, take some raw materials and follow the design to create our finished object (then drive away in
it!). In our software world, we will create our design (the Java class), take some memory and form
our object(s) out of it.
Of course, we ourselves don’t manufacture these objects ourselves; we define the features of an
object in a class definition and then get Java (the "object factory") to create objects of this class for
us.
Klasse begrebet
En klasse (class) definerer en ny datatype og
operationer på den er samlet i en enhed
Data (kaldes instanse variabler i Java)
Operations (kaldes instanse metoder i Java)
Klasse begrebet
{
}
public boolean start()
public boolean start()
private String model;
private String model;
private int speed;
private int speed;
public byte accelerate()
public byte accelerate()
Car
Operations
Data
Class Definition
Noter til
Side 6 af 124
A class is a template for building multiple objects with similar features. A class encapsulates all the
features of an object, i.e. its data structure and its behaviour. So, when you write an object-oriented
program, you don't write code for individual objects. Instead, you define the data structure and the
behaviour (or operations) of a class of objects. Then, when you want to create objects of this class,
you get Java to create instances of this class. All objects of the same class have the same data
structure and behaviour (as defined in the class), but each object is independent of every object of
its class. In other words, each object can store its own values in the data structure defined by the
class.
Klasser og objekter
Klasser og objekter
En klasse er en skabelon for bygningen af objekter
Et hvert objekt er en instanse af en klasse
Car Object 1
model: "Ford"
speed: 105
model: "BMW"
speed: 140
Car Object 2
Class Definition
public boolean start()
public boolean start()
private String model;
private String model;
private int speed;
private int speed;
public byte accelerate()
public byte accelerate()
Car
A class is a template for building objects of that class. In object-oriented terminology, an object is
an instance of a class. This simply means that each object of that class has the same data structure
and operations. However, the values held in this data structure are unique to each object. Such data
is therefore called instance data. Furthermore, the operations of an object act on that object's
instance data.
Noter til
Side 7 af 124
Skabelse af objekter
Skabelse af objekter
Objekter skabes vha. new
operatoren
Returnerer en reference til et objekt
Car car1 = new Car();
Car car1 = new Car();
Car car2 = new Car("BMW");
Car car2 = new Car("BMW");
model:null
speed:0
model:"BMW"
speed:0
objectRef = new ClassName();
Objects are created by using the new operator with the class of the object and any arguments
needed by the class' constructor. A constructor is a special method supplied by the class which is
designed to initialise an object's data when it is first created. The parentheses are mandatory, even
if you want to invoke a constructor that has no parameters (as in the first example on the slide).
On the slide, we create two Car objects; in other words, two instances of the Car class. Each Car
object has the same structure, but is completely independent.
new operatoren
new operatoren
Allokerer hukommelse til et nyt objekt
Kalder klassens constructor
bruges til at initialisere objektets instanse variabler
En 'no-arg' constructor leveres pr. default
Der kan være flere forskellige constructors
Der returneres en reference til et nyt objekt
Car car2 = new Car("BMW");
Car car2 = new Car("BMW");
car2
model:"BMW"
speed:0
Reference
Object
The new operator allocates an appropriate amount of memory for the new object and then calls the
class' constructor. As previously mentioned, a constructor is a special method supplied by the class.
You will learn more about constructors towards the end of the chapter.
Noter til
Side 8 af 124
The new operator also returns a reference to the newly-created object. To refer to this object in the
future, you'll need to store this reference in a variable as shown in the example on the slide. Note
that the declaration of an object reference and the creation of an object are completely independent.
This means that you could rewrite the example on the slide as follows:
Car car2; // declare a variable capable of holding a reference
// to an object of the Car class
. . .
. . .
car2 = new Car("BMW"); // create a new Car object and assign its
// reference to the variable car2
null Referencen
null Referencen
En objekt reference er null indtil den initialiseres
Man kan sammenligne en objekt reference med null
Man kan sætte en objekt reference til null. Herved frigøres
pladsen i hukommelse vha. garbage collector
Car car1;
. . .
if (car1 == null)
{
System.out.println("Not initialised");
car1 = new Car();
}
. . .
car1 = null;
Car car1;
. . .
if (car1 == null)
{
System.out.println("Not initialised");
car1 = new Car();
}
. . .
car1 = null;
When you declare an object reference, as in:
Car car1;
the variable car1 is initialised with a special reference called null, which indicates that the
reference does not refer to any object. null is a keyword in the Java language, so you can use it
with the equality operator to check whether an object reference has been initialised or not.
When you have finished using an object, you can set its object reference to null. This decrements
the object's (internal) reference count, which determines an object's lifetime. When the reference
count reaches zero, the object will be marked for garbage collection so that its memory can be
reclaimed. In practice, you only need to set an object reference to null in special cases, because
once a variable that holds an object reference goes out of scope, the object's reference count will be
decremented automatically.
Noter til
Side 9 af 124
Tildeling af objekt reference
Tildeling af objekt reference
Tildeling af en reference
til en
anden resulterer
i to
referencer til det samme objekt.
car2
Car car1 = new Car();
Car car1 = new Car();
car1
model:""
speed:0
Car car2 = car1;
Car car2 = car1;
As previously mentioned, when you declare an object reference, it is initialised to null. Before
you can use that reference, you must initialise it. Typically, you would initialise it with a reference
to a new object, e.g.
Car car1 = new Car();
Now, what if you want to declare a second variable of the same class? Since you already have a
reference to an object of this class, you could initialise this variable as follows:
Car car2 = car1;
This is perfectly legal, but as the diagram on the slide shows, you still have only one object. When
you assign an object reference to another object reference, you end up with two references to the
same object, not a copy of the other object. You can access the same object through either
reference, but there is still only one object. It is very important to remember this, particularly when
you pass an object reference to a method, as we will see in the next chapter.
You can, of course, change either reference to refer to a different object without affecting the other
reference. However, if you really need a separate object, rather than multiple references to a single
object, then you must either create a new object or invoke an object's clone() method. As its
Car car2 = car1.clone();
(assuming that, if necessary, an appropriate clone() method is defined in the Car class)
The implementation of a clone() method is beyond the scope of this chapter, so for further
information, please consult the JDK documentation.
Noter til
Side 10 af 124
Definering af en klasse
Nøgle begreber ved definition af en klasse:
En valgfri modifier
Nøgleordet class efterfulgt af klassenavn
Klassens krop indeholder
En eller flere instance variabler
En eller flere instance metoder
Definering af en klasse
modifier class ClassName {
// instance variable(s)
modifier varType var1;
. . .
// instance method(s)
modifier returnType method1( argumentList ) {
. . .
}
. . .
}
modifier class ClassName {
// instance variable(s)
modifier varType var1;
. . .
// instance method(s)
modifier returnType method1( argumentList ) {
. . .
}
. . .
}
This slide shows the syntax of a class definition. Every Java program needs at least one class
definition, even if it only contains a main() method.
The class definition starts with the keyword class followed by the class body (in braces). It may
be preceded by a modifier such as public. If you omit the modifier public, the class will be
visible only to other classes within the same package. (A package is a collection of related classes.)
The class body contains declarations of instance variables together with definitions of instance
methods and constructors. The order in which these are placed in the class body is unimportant, but
in all of our examples, we have put instance variables ahead of instance methods. However, you
will find that many Java programmers (especially those that have a C++ background) prefer to
define the instance methods first (since these normally constitute the public user interface of the
class) and 'hide' the instance variables at the bottom.
In the following slides, we will develop a class definition for our Car class.
Noter til
Side 11 af 124
Metode og variable modifiers
Metode og variable modifiers
Alle variabler og metoder har modifiers der angiver
adgangskontrol
PRIVATE - kan bruges af klassen selv
PACKAGE - kan bruges i aktuelle pakke
PROTECTED - kan bruges i klassen selv, subklasser og i aktuelle
pakke
PUBLIC - kan bruges overalt, hvor klassen er tilgængelig
Metode modifiers
Abstract – skal implementeres i subklasser
Static – klasse metode, fælles for alle instancer af klassen
Final –kan ikke overrides i subklasser
Class modifiers
Class modifiers
PUBLIC
Alle kan erklære referencer af objekter af denne klasse
ABSTRACT
Nogle af klassens metoder er abstract og skal
implementeres af subklasser
FINAL
Ingen subklasser
STRICT FLOATING POINT
Floating point operationer evalueres strengt.
Giver ens resultater i alle JVM
Noter til
Side 12 af 124
Instanse Variabler
Instanse Variabler
Instanse variabler erklæres som lokale variabler
public class Car {
public String model;
public int speed;
public byte currentGear;
. . .
}
public class Car {
public String model;
public int speed;
public byte currentGear;
. . .
}
Car car1 = new Car();
Car car2 = new Car();
Car car1 = new Car();
Car car2 = new Car();
car1
model: null
speed: 0
currentGear: 0
car2
model: null
speed: 0
currentGear: 0
Hver instanse af en klasse har en identisk datastruktur
Instance variables must be declared within the class definition as shown in the example on the slide.
To keep things simple, we have declared these instance variables as public to allow users of the
class to access them. This is generally undesirable as we will see later, and once we discover how
to write instance methods, we'll make them private to prevent them from being manipulated
directly by users of the class.
We have also created two instances of this class; in other words, two Car objects referenced by
car1 and car2, respectively. Although these objects are completely independent, they have an
identical data structure. In other words, each object has its own instances of the instance variables
that we declared in the definition of the Car class.
Definering af Instanse Metoder
Definering af Instanse Metoder
Instanse metoder er metoder der operere på instanser af klassen
Instanse metoder har direkte adgang til instanse variabler
public class Car {
private int speed; // now private
private byte currentGear; // " "
private byte numGears = 5; // 0 = neutral
. . .
public boolean selectGear(byte newGear) {
boolean result = false;
if (newGear >= 0 && newGear <= numGears) {
currentGear = newGear;
result = true;
}
return result;
}
public class Car {
private int speed; // now private
private byte currentGear; // " "
private byte numGears = 5; // 0 = neutral
. . .
public boolean selectGear(byte newGear) {
boolean result = false;
if (newGear >= 0 && newGear <= numGears) {
currentGear = newGear;
result = true;
}
return result;
}
Noter til
Side 13 af 124
Instance methods are methods that are defined in a class and operate on instances of that class.
Inside a method, you can declare local variables. Not e that the scope of a local variable is limited
to the block in which it is declared. This means that if you declare a local variable within a method,
if cannot be accessed from outside of that method.
In the example on the slide, we have defined a single instance method selectGear() that takes
a single argument: newGear and returns a boolean. The method declares a local variable
result, which allows us to provide a single point of return prior to the closing brace. Notice how
the instance method ensures that the value of newGear is valid before updating the instance
variable currentGear. The instance variables are now marked as private, so it's now
impossible for a user of the Car class to specify an invalid gear!
Indkapsling
Indkapsling
Instanse
variables bør være erklæret private
Kun instanse metoder kan tilgå private
instanse variabler
Adskiller
public grænsefladen fra den interne
implementation
public class Car {
private int speed;
private byte currentGear;
. . .
public int getSpeed() {
return speed;
}
public boolean selectGear(byte newGear) {
. . .
}
public class Car {
private int speed;
private byte currentGear;
. . .
public int getSpeed() {
return speed;
}
public boolean selectGear(byte newGear) {
. . .
}
Cannot access
private instance
variables of car1
Car car1 = new Car();
. . .
if (car1.speed >= 55) // error
car1.selectGear(5); // OK
. . .
Car car1 = new Car();
. . .
if (car1.speed >= 55) // error
car1.selectGear(5); // OK
. . .
Encapsulation is a key concept in object-oriented programming. A well-defined class should de-
couple its public user interface from its internal implementation. To achieve this, all instance
variables of a class should be made private in order to hide them from users of the class. Only
the instance methods of a class can access the private instance variables of that class.
Users of the Car class must then invoke one of the public methods of the Car class in order to
access or change the state of a Car object. As shown on the slide, it is impossible for a user of our
Car class to access the instance variable speed directly.
If at some point in the future, we want to change the gearbox in our Car class, say, to increase the
number of gears or to replace it by an automatic version, all we need to do is to modify the class
definition. Provided we don't change the public user-interface of our class (i.e. we retain the same
public instance methods with exactly the same signatures), we won't affect users of our class. In
other words, we won't break any existing code that uses the Car class.
Noter til
Side 14 af 124
Constructors
Constructors
Når et objekt skabes,
initialiseres dets instanse
variables som følger:
Primitive typer sættes til nul
boolean typer sættes til false
Object references sættes til
null
For at sikre ordentlig initialisering af instanse variabler
skal en klasse tilbyde en eller flere
constructors
En constructor er en speciel metode der automatisk
kaldes når objektet skabes.
Erklæres normalt
public
Har samme navn som klassen
Ingen retur type specificeret
When an object is created, its instance variables are initialised to their default values as shown on
the slide. However, you will generally need to provide one or more constructors in a class in order
to initialise its instance variables properly and to allow users of the class to specify the initial state
of a new object. For example, with our Car class, we have already seen examples such as:
Car car3 = new Car("BMW");
To allow a user to create an object in this way, the Car class must provide a constructor that
initialises the state of a Car object with the specified make of car.
A constructor is a special method that is called automatically (by the run-time system) when an
object is created. A constructor must have the same name as the class. It may have arguments, but
it must not specify a return type. Unless you want to restrict who can create instances of the class,
the constructor should be declared as public.
If you do not provide any constructors in a class, a default 'no-arg' constructor is provided for you.
This constructor takes no arguments and does nothing, but does at least allow objects to be created.
Note that if you want both a no-argument constructor and one or more constructors with arguments,
you must explicitly provide your own no-argument constructor.
Noter til
Side 15 af 124
Definering af Constructors
Definering af
Constructors
En klasse definition kan indeholde
mange constructors
hver constructor skal have forskellig signature (navn +argument list)
Ingen constructor kan have en return type (heller ikke void)
public class Car {
private String model;
. . .
public Car() {
. . .
}
public Car(String make) {
model = make;
. . .
}
}
public class Car {
private String model;
. . .
public Car() {
. . .
}
public Car(String make) {
model = make;
. . .
}
}
Car car1 = new Car();
Car car2 = new Car("Audi");
Car car3 = new Car("BMW");
. . .
Car car1 = new Car();
Car car2 = new Car("Audi");
Car car3 = new Car("BMW");
. . .
If you want to provide more than one constructor in a class, each one must have a different
signature. Because each constructor must have the same name (i.e. the name of the class), this
simply means that each constructor must have different numbers or types of arguments.
In the Car class, we have decided to provide two simple constructors: one with no arguments and
the other with a single String argument for the make of the car. The second constructor simply
initialises the instance variable model with the specified make of car. As shown on the slide, users
of this class can now create cars of different makes.
You'll learn more about constructors in the next chapter.
this-Referencen
this Referencen
En instance metode kan anvende
this til explicit at
identificere objektet selv
Skal f.eks. anvendes hvis en
metodes argument skjuler
en instanse variabel
Kan også anvendes til at overføre en reference til det
aktuelle objekt
public class Car {
private int cruiseSpeed;
. . .
public void setCruiseSpeed(int cruiseSpeed) {
this.cruiseSpeed = cruiseSpeed;
}
}
public class Car {
private int cruiseSpeed;
. . .
public void setCruiseSpeed(int cruiseSpeed) {
this.cruiseSpeed = cruiseSpeed;
}
}
In any instance method, an implicit this reference is used in any unqualified reference to an
instance variable (or an instance method) to refer to "this object". For example, the getSpeed()
method on the previous slide is equivalent to:
Noter til
Side 16 af 124
public int getSpeed() {
return this.speed;
}
There are only two circumstances where you need to use an explicit this reference.
1. Where the name of an instance variable is hidden by a formal argument of an instance method.
For example, on the slide, the instance method setCruiseSpeed() has an argument called
cruiseSpeed that hides the instance variable cruiseSpeed. Therefore, inside the method, we
need to explicitly specify this.cruiseSpeed in order to access the instance variable
cruiseSpeed. However, deliberately hiding variables in this way is considered to be bad
practice as it can lead to errors that are difficult to trace. A better solution is to rename either the
instance variable or the formal argument.
2. Where you need to pass a reference to the current object as an argument to another method or
constructor. For example, when an applet creates a thread, it has to pass a reference to itself to one
of the constructors of the Thread class. We'll see this when we discuss threads in a later chapter.
Overloading
Overloading
Mange metoder kan have det samme navn, sålænge de
har forskellige signaturer
Skal have forskelligt antal eller typer af argumenter
Forskellige retur typer er ikke tilstrækkeligt
public class Car {
private int speed;
. . .
public void accelerate( ) {
speed += 5;
}
public void accelerate(byte speedIncr) {
speed += speedIncr;
}
public class Car {
private int speed;
. . .
public void accelerate( ) {
speed += 5;
}
public void accelerate(byte speedIncr) {
speed += speedIncr;
}
Car car1 = new Car();
. . .
car1.accelerate();
car1.accelerate(20);
Car car1 = new Car();
. . .
car1.accelerate();
car1.accelerate(20);
Two or more methods in a class can have the same name provided they have different signatures.
A method's signature is formed from its name together with the number and types of its arguments.
The method's return type is not included.
Defining two or more methods with the same name but different signatures is called method
overloading. This is very useful where several methods perform similar operations as shown in the
example on the slide. When a user of a class calls an overloaded method, the compiler chooses the
correct method to call by comparing the argument types passed in the call with all the methods of
that name in the class definition. If the compiler cannot find a compatible match (casting if
necessary) or if more than one match is possible, the compiler will flag an error.
Incidentally, overloaded methods can have different return types, but they cannot differ only in
return types.
Noter til
Side 17 af 124
Værdioverførsel til metoder
Værdioverførsel
Når selectGear() metoden kaldes:
Variablen g tildeles værdien af den kaldendes
variable,
gear
selectGear
() kan ændre værdien af g uden det påvirker værdien
afgear i programkoden, hvorfra metoden blev kaldt.
Car car = new Car();
. . .
. . .
byte gear = 5;
car.selectGear(gear);
System.out.println(
"Gear = " + gear);
. . .
Car car = new Car();
. . .
. . .
byte gear = 5;
car.selectGear(gear);
System.out.println(
"Gear = " + gear);
. . .
class Car {
private int currentGear;
. . .
void selectGear(byte g)
{
if (g > 4) g = 4;
currentGear = g;
}
. . .
class Car {
private int currentGear;
. . .
void selectGear(byte g)
{
if (g > 4) g = 4;
currentGear = g;
}
. . .
gear: 5 g: 5 4
copy of
value
It is very important to understand the difference between passing a primitive value and passing an
object reference as an argument to a method.
When a method is called, each formal argument becomes a local variable in the scope of the method
and is initialised with the value passed in the corresponding actual argument of the call. In other
words, the initial value of an argument variable in the method is a copy of the value passed in the
call to the method.
This way of passing arguments to a method is known as "call by value". The key implication of
"call by value" is that a method can change the value of an argument variable without affecting a
variable in the code that called the method.
This is clearly demonstrated by the example on the slide. Here, the method selectGear() has a
single argument of type byte, i.e a primitive. When the call is made, the value 5 is copied into the
argument variable g in the method selectGear(). If selectGear() subsequently sets g to
4, this has no affect on the value of gear in the caller's code.
Noter til
Side 18 af 124
Overførsel af referencer til metoder
Overførsel af referencer til Metoder
Når addRadio() metoden kaldes :
Variablen r tildeles værdien af den kaldendes variablen, mr
Både metoden og den kaldende kode har en reference til samme objekt
.
Der er stadig tale om værdioverførsel da referencen kopieres til metodens
variabel
Car car = new Car();
Radio mr;
. . .
mr = new Radio();
car.addRadio(mr);
Car car = new Car();
Radio mr;
. . .
mr = new Radio();
car.addRadio(mr);
class Car {
private Radio radio;
. . .
void addRadio(Radio r)
{
radio = r;
radio.setVolume(20);
}
. . .
class Car {
private Radio radio;
. . .
void addRadio(Radio r)
{
radio = r;
radio.setVolume(20);
}
. . .
mr r
copy of
reference
Type: Sony
Model: CDX-3100
Radio
Object
The picture changes when a method has an argument that is a reference to an object. The initial
value of the argument variable in a method is still a copy of the value passed in the call to the
method. However, because the argument is a reference, it is the reference that is copied, not the
object itself. The end result is that the method has a reference to the caller's object, which is
equivalent to "call by reference".
The key implication of "call by reference" is that any change that the method makes to the object
through its reference affects a variable in the caller's code and persists after the method returns.
Again this is clearly demonstrated by the example on the slide. Here, the method addRadio()
has a single argument r, which is a reference to a Radio object. When the call is made, the
reference mr to a Radio object is copied into the argument variable r in the method
addRadio(). The method itself copies this reference to an instance variable radio (so now we
have three references to the Radio object). Finally, the addRadio() method calls the
setVolume() method of the Radio object. Clearly, this change persists after the method
returns, because there is only one radio object. This may or may not be a problem depending on the
application. In this example, if a new Radio object is created before each call to addRadio(),
it is not a problem (because the caller is effectively giving a new Radio object to each Car
object).
Incidentally, in this particular example, it is also worth noting that there is a privacy issue in the
implementation of addRadio(). Because the caller retains a reference to the Radio object after
the addRadio() method returns, the caller of addRadio() can manipulate the Radio object in
a Car object even though radio is a private instance variable of the Car class. To get round this
problem, addRadio() should clone another Radio object, rather than just copying the reference
passed in.
Noter til
Side 19 af 124
Overloading Constructors
Overloading Constructors
Hvis ingen constructor er defineret i en klasse, tilbyder compileren
en 'no-arg' constructor
Hvis en constructor er defineret i en klassen og der er behov
for en
no-arg constructor, må klassen selv tilbyde en sådan
Hvis der forekommer flere constructors skal de have forskellige
signatur
public class Car {
. . .
public Car() {
. . .
}
public Car(String make) {
. . .
}
. . .
}
public class Car {
. . .
public Car() {
. . .
}
public Car(String make) {
. . .
}
. . .
}
As mentioned previously, a constructor is a special method that is called automatically when an
object is created. A constructor must have the same name as the class. It may have arguments, but
it must not specify a return type.
If you do not provide any constructors in a class, a default 'no-arg' constructor is provided for you.
This constructor takes no arguments and does nothing. If you want both a no-argument constructor
and one or more constructors with arguments, you must explicitly provide your own no-argument
constructor.
As with overloaded methods, if you want to provide more than one constructor in a class, each one
must have a different signature. Because each constructor must have the same name anyway, this
simply means that each constructor must have different numbers or types of arguments.
In the example on the slide, the Car class has two simple constructors: one with no arguments and
the other with a single String argument for the make of the car.
Noter til
Side 20 af 124
Sammenhæng mellem Constructors
Sammenhæng mellem Constructorer
En constructor kan kalde
en anden
constructor
vha.
this()
Gør det unødvendigt, at gentage kode i flere forskellige constructors
Kaldet til this() skal være den første sætning i constructor
Argumenterne til this()
skal matche den
kaldte constructor
public class Car {
private String model;
public Car() {
this("Ford"); // default car
}
public Car(String make) {
model = make;
. . .
}
. . .
public class Car {
private String model;
public Car() {
this("Ford"); // default car
}
public Car(String make) {
model = make;
. . .
}
. . .
A useful feature of Java is that you can call one constructor from another. This means that you can
avoid having to duplicate complex initialisation code across multiple constructors.
Klasse variabler (static)
Klasse variabler (static)
En klasse variabel tilhører en klasse og er fælles for alle
instancer af klassen
Erklæres static i klasse definitionen
Der er kun en dvla, men et regNumber per instanse
Instanse metoder kan tilgå både instanse og klasse variabler
public class Car {
private static LicenseAgency dvla; // class var
private LicensePlate regNumber; // instance var
. . .
public class Car {
private static LicenseAgency dvla; // class var
private LicensePlate regNumber; // instance var
. . .
public void register() {
regNumber = dvla.getNextLicense(); }
public void register() {
regNumber = dvla.getNextLicense(); }
regNumber
Car Class
dvla
regNumber regNumber
A class variable (also called a static variable) is a variable that belongs to a class and is common to
all instances of that class. In other words, there is only one instance of a class variable, no matter
how many instances of that class there are. So, if an instance method accesses a class variable of a
class, it will see the same value in that variable as all the other methods of that class.
Class variables are declared using the keyword static. In the example on the slide, we have
declared dvla as a class variable, because all car objects in one country are registered with the
same license agency (in the UK, the Driver and Vehicle Licensing Agency). We've also declared
dvla as private, because it only needs to be accessed by methods of the Car class.
Noter til
Side 21 af 124
Klasse metoder (static)
Klasse metoder (static)
En klasse metode deles af alle instanser af klassen
Brugbar til at manipulere klasse variabler
Har ingen this reference
public static void changeLA(LicenseAgency newLA)
{ dvla = newLA;}
public static void changeLA(LicenseAgency newLA)
{ dvla = newLA;}
Kan kun indirekte tilgå instance variabler eller instance
metoder
public static boolean compare(Car car1, Car car2)
{ return (car1.regNumber == car2.regNumber
); }
public static boolean compare(Car car1, Car car2)
{ return (car1.regNumber == car2.regNumber); }
For at kalde en klasse metode eksternt, brug klassens navn
Car car1 = new Car();
Car car2 = new Car();
if (
Car.compare(car1, car2)) . . .
Car car1 = new Car();
Car car2 = new Car();
if (Car.compare(car1, car2)) . . .
A class (or static) method is a method that belongs to a class and is shared by all instances of that
class. Unlike an instance method, a class method does not operate on a single object, so it does not
have a this reference. Because no instances may exist, a class method can access only the class
variables and class methods of its class.
Class methods are the ideal way to access class variables. In fact, they are the only way if no
instances of the class currently exist. For example, the changeLA() method on the slide changes
the license agency of all cars.
Class methods are also useful where you have references to more than one object, such as in the
compare() method on the slide, or when an object is not really necessary to perform a task (such
as a maths function).
A user of a class can call a class method by specifying the class name instead of an object reference
(i.e. on the left-hand side of the dot operator) as demonstrated in the final example on the slide.
Klasse metoder <> instance metoder
Klasse metoder <> instanse metoder
Instanse metoder har behov for et objekt, det har klasse metoder ikke
public class Car {
private static LicenseAgency dvla;
private byte numSeats;
. . .
public static boolean
checkLicense(LicensePlate lp) {
return(dvla.check(lp));
}
public byte getSeats() {
return(numSeats);
}
}
public class Car {
private static LicenseAgency dvla;
private byte numSeats;
. . .
public static boolean
checkLicense(LicensePlate lp) {
return(dvla.check(lp));
}
public byte getSeats() {
return(numSeats);
}
}
Car car1 = new Car();
. . .
Car.checkLicense(lp);
Car.getSeats();
byte b = car1.getSeats();
Car car1 = new Car();
. . .
Car.checkLicense(lp);
Car.getSeats();
byte b = car1.getSeats();
Noter til
Side 22 af 124
Although you can mix instance and class variables/methods in the same class, it's often cleaner to
separate class variables and methods out to a separate class. For example, a BankAccount class
could have a class variables for the total number of BankAccount objects and the interest rates
for various types of account, in addition to an instance variable to hold a reference to each
individual BankAccount object. However, a better way might be to have two classes: one for the
Bank (or BankBranch) and the other for a BankAccount. Most of the class variables will now
be held in the Bank class, whereas most of the instance variables will be held in the
BankAccount class. A further benefit of this approach is that you can now have multiple
instances of the Bank (or BankBranch) class.
Exempler i klasse og instans metoder
Exampler i Java
Math.sqrt() er en public klasse metode
Math er en klasse
sqrt() er en public klasse metode
System.out.println() er en instanse metode
System er en klasse
out er en public klasse variabel der referere til et objekt af
PrintStream class
println() er en instnace metode i PrintStream class
main() er en public klasse metode
The Math class provides class methods to compute many mathematical functions, such as
trigonometric functions and logarithms. It also provides a number of class constants such as e
(2.71828...) and π (). All mathematical operations are carried out in double
precision.
The System class provides class methods to represent the state of the entire system.
System.out is a public class variable that refers to an object of the PrintStream class that
represents the standard output stream. So, although println() is an instance method of the
PrintStream class, you don't need to instantiate this class before calling
System.out.println() method - it's already been done for you by the System class.
When you run a Java application, the VM locates and calls the main() method of that class. So,
although everything in a Java program must be contained within a class, you don't need to
instantiate it if main() calls only class methods. However, if main() needs to call any instance
method (or access any instance variables) of its own class, it must first instantiate itself. For
example:
public class Car {
{
. . .
public boolean startEngine()
Noter til
Side 23 af 124
{
. . .
}
public static void main(String[] args) {
Car myCar = new Car();
myCar.startEngine();
}
}
This technique can be useful for stand-alone testing of a class.
Final variabler
Final Variaber
En final variabel er en konstant
A final variable can only be initialised once
skal initialiseres før den bruges
public final class Color {
public final static Color black = new Color(0,0,0);
public final class Color {
public final static Color black = new Color(0,0,0);
C and C++ programmers will be used to using #define to define constant values. Final
variables provide the same functionality in Java.
In Java 1.0 only static and instance variables could be declared final, but in Java 1.1 local variables
and method parameters may also be final.
All final variables must be initialised before they can be used. In Java 1.0 this must be done during
the declaration of the final variable; but this restriction was relaxed for Java 1.1 which allows
“blank” final variables. These are initialised when first assigned and are subsequently read only.
[As we shall see when we come to discuss Java interfaces, all variables in an interface are implicitly
both static and final.]
Noter til
Side 24 af 124
Eksempler Klasser og Objekter
Eksempler
Eks. 1
Opgave Person
Eks. 2
JPL s. 58
Class Person
class Person{
private static long nextId = 0;
protected long idNum;
private String navn = " ";
private int alder = 0;
Person(){
idNum = nextId++;
System.out.println("Person oprettet");
alder = 0;
}
Person(String nytNavn , int nyAlder){
this();
alder = nyAlder;
}
public String getNavn(){
return navn;
}
public void putNavn(String nytNavn){
}
public int getAlder(){
return alder;
}
public void putAlder(int nyAlder){
alder = nyAlder;
}
protected void udskriv(){
Noter til
Side 25 af 124
System.out.println("Person data: "+ print());
}
protected String print(){
return (idNum+ " "+ getNavn()+ " " + getAlder());
}
}
class TMC_Person{
TMC_Person(){};
public static void main(String[] args){
int tæller = 0;
int kata1 = 0;
int kata2 = 0;
int kata3 = 0;
/*Person p = new Person("Lasse",36);
System.out.println("Navn "+ p.getNavn());
System.out.println("Alder "+ p.getAlder());
*/
Person[] ptabel = new Person[5];
for(int i=0;i<ptabel.length;i++){
System.out.println("Indtast navn og alder");
ptabel[i] = new Person(rhs.RHSIo.readString(), rhs.RHSIo.readInt());
}
for(int i=0;i<ptabel.length;i++){
System.out.println("Navn "+ ptabel[i].getNavn());
System.out.println("Alder "+ ptabel[i].getAlder());
}
while(tæller != 5){
if(ptabel[tæller].getAlder() < 15){
kata1++;
}
else if(ptabel[tæller].getAlder() > 67){
kata3++;
}
else{
kata2++;
}
ller++;
}
System.out.println("Personer under 15" +kata1);
System.out.println("Personer mellem 15 og 67" +kata2);
System.out.println("Personer over 67" +kata3);
}
}
Noter til
Side 26 af 124
Kapitel 2 Subklasser og arv
Poul Henriksen 1
JAVA programmering/2000
Subklasser
og arv
En subklasse udvider superklassens kontrakt
En klasse kan arve attributter og metoder fra
en
anden klasse
Den
oprindelige klasse kaldes for
s
uperklassen
Den nye klasse kaldes
subklassen
Subklassen kan
:
Anvende alle egenskaber i superklassen
Override metoder i superklassen
Tilføje nye attributter og metoder
Eksisterende kode I superklassen kan genbruges af
subklassen
Nye klasser kan defineres udelukkende udfra deres forskel
til en eksisterende klasse
Examples of inheritance are ubiquitous in our model of the real world. Our definition of a cat
inherits the features of our definition of a mammal, which in turn inherits the features of our
definition of an animal. A chair and a table both inherit the features of furniture. A taxi is a car.
Notice that subclasses must add features to the superclass; they can take on features of the
superclass, add or (slightly) modify features, but cannot remove features.
Many different terms are used with inheritance, even by Java people, as there is really no consensus
in the wider object-oriented community. Superclass-subclass equates to base-derived, and often to
parent-child (although confusing this is also used occasionally to refer to whole-part relationships).
Arv
Noter til
Side 27 af 124
Arve hiraki
Poul Henriksen 3
JAVA programmering/2000
Arve hierarki
Brava
extends
Bravissimo
Superclass
Subclass
Bravissimo klassen extends
Brava klassen
Brava definerer bestemte
metoder og instance variabler
Bravissimo klassen kan:
Override metoder i Brava klassen
Tilføje nye metoder
Tilføje nye
instance variabler
Brugere af klassen Bravissimo
kan:
Kalde alle
public metoder defineret i
Brava klassen
Kalde alle
public metoder defineret i
Bravissimo klassen
Note that Java only supports single inheritance and only in a single tree. Therefore, any class that
does not explicitly extend another class implicitly extends the Object class. In other words, the
Object class is the only class that does not have a superclass.
extends
Poul Henriksen 4
JAVA programmering/2000
Herved arver Bravissimo klassen variabler og metoder
fra Brava klassen
Et Bravissimo objekt er en (IS A) Brava objekt
extends
For at lave en subklassen anvendes ordet extends
public class Brava extends Car {
. . .
}
public class Brava extends Car {
. . .
}
public class Bravissimo extends Brava {
. . .
}
public class Bravissimo extends Brava {
. . .
}
When you define a subclass, you need only to provide code for the things in the subclass which are
different to the superclass.
Incidentally, if you have experience with another object-oriented languages such as C++, note that
Java only allows single inheritance and then only in an inheritance tree with a single root (the
Object class). In the next chapter, we will see that the use of interfaces provides a more coherent
and less ambiguous approach to allowing a class to provide for multiple concepts.
Note that we can say that a Bravissimo object is a Brava object, because a Bravissimo
object has all the characteristics (variables and methods) of a Brava object. Therefore, a
Noter til
Side 28 af 124
Bravissimo object may be used in place of a Brava object (but not the other way round). This
"is a" relationship is a key feature of inheritance.
Semantik af arv
Poul Henriksen
5
JAVA programmering/2000
Et subklasse objekt er en (IS A) type af superklasse objektet
En Bravissimo objekt er en type af Brava objektet
Semantik af arv
En subklasse arver alle instance variabler og metoder
fra superklassen
public class Brava {
private int numDoors;
private Engine eng;
. . .
}
public class Brava {
private int numDoors;
private Engine eng;
. . .
}
public class Bravissimo extends Brava {
private TurboUnit turbo;
. . .
}
public class Bravissimo extends Brava {
private TurboUnit turbo;
. . .
}
eng
num
Doors
Brava
object
turbo
eng
num
Doors
Bravissimo
object
Instance variables should normally be declared as private, which means that instances of
subclasses will have these values, but will not be able access them directly. In our example,
numDoors and eng are private to the Brava class and cannot be directly accessed by the
Bravissimo class. Therefore, if we change the implementation of a superclass, we will not need
to trawl through all its subclasses to see if they are impacted by the change.
Note that as far as class variables are concerned, there is only one 'instance', irrespective of how
many subclasses there are.
Subklassens constructor
Poul Henriksen 6
JAVA programmering/2000
Subklassens constructor
En subklasse arver ikke nogen af superklassens constructors
Constructors er ikke metoder.
Nedarves ikke.
Når et objekt skabes kaldes superklassens no-argument
constructor automatisk
En subklasse kan ekspicit kalde superklassen constructor vha.
super()
super() skal være
den første sætning I constructoren
Argumenterne til super() skal matche dem der findes i superklassens
constructor
public class Bravissimo extends Brava {
public Bravissimo (int d, Engine e, TurboUnit t)
{
super(d, e);
turbo = t;
}
. . .
public class Bravissimo extends Brava {
public Bravissimo (int d, Engine e, TurboUnit t)
{
super(d, e);
turbo = t;
}
. . .
Noter til
Side 29 af 124
A class does not inherit any constructors from its superclass. Therefore the class has only the
constructors explicitly defined in that class or, if none are defined, the default no-arg constructor.
Objects are always constructed from the top class down to the bottom class (i.e. from the Object
class down to the class that is being instantiated (the argument to new) ). This ensures that a
constructor in a subclass can rely on proper construction of its superclasses. However, this works
only if the superclass has a no-arg constructor, as the compiler could not guess which arguments
you may wish to pass to the superclass' constructor. If the superclass does not have a no-arg
constructor, you can use super() to explicitly call a specific constructor in the superclass. The
arguments to super() must, of course, match those of the target constructor.
Note that when an object is created, the order of construction is as follows:
1. Its instance variables are initialised to default values:
Zero for primitives
false for booleans
\u0000 for characters
null for object references
2. Its constructor is called
Calls the constructor of its superclass (either implicitly or explicitly)
Initialises its instance variables through their initialisers (if any)
Executes the body of the constructor
Overriding
Poul Henriksen 7
JAVA programmering/2000
Overriding
Subklassen arver alle metoder fra superklassen
Subklassen kan ændre funktionaliteten af enhver af de metoder der
er adgang til i subklassen vha. overriding
Signatur og retur typer skal være ens
Herved skjules metoder med samme signatur i superklassen
Static metoder kan ikke override instance metoder (og omvendt)
public class Brava {
public int getSpeed() {
return (getRevs()/100) * gear;
}
...
public class Brava {
public int getSpeed() {
return (getRevs()/100) * gear;
}
...
public class Bravissimo extends Brava {
public int getSpeed() {
return (getRevs()/100) * gear * turbo.boost();
}
...
public class Bravissimo extends Brava {
public int getSpeed() {
return (getRevs()/100) * gear * turbo.boost();
}
...
A subclass inherits all of the instance methods of its superclass. However, a subclass can modify
the behaviour of a method in a superclass by overriding it. This means that the subclass defines a
method with exactly the same signature and return type as one in a superclass (not necessarily its
immediate superclass). The method in the subclass then effectively 'hides' the method in the
superclass. Note that it is up to you as the programmer to ensure that the method in the subclass has
the same semantics as the one it is overriding.
Do not confuse method overloading with method overriding. Method overloading is where you
define multiple methods with different signatures. Method overriding is where you provide a
method with exactly the same signature as a method in a superclass.
Noter til
Side 30 af 124
Kald af superklassens skjulte metoder
Poul Henriksen 8
JAVA programmering/2000
Kald af superklassens skjulte metoder
En metode i subklassen kan kalde
en
skjult metode i
superklassen (undgår gentagelser i koden)
Superklassens metode kaldes vha. super reference
super refererer til superklassen
Når super.method() kaldes,
vil
runtime systemet søge
op i
arve
hierarkiet efter en metode der matcher
signaturen
public class Bravissimo extends Brava {
. . .
public int getSpeed() {
return super.getSpeed() * turbo.boost();
}
}
public class Bravissimo extends Brava {
. . .
public int getSpeed() {
return super.getSpeed() * turbo.boost();
}
}
As previously mentioned, when a subclass overrides a method in a superclass, it hides that method,
not only from a user of the subclass, but from the subclass itself. To avoid having to duplicate code
contained in the hidden method, which is generally undesirable for maintenance reasons, a method
can use the super reference to call the original hidden method in a superclass. The keyword
super is similar to this, except that it acts as a reference to the current object as an instance of
its superclass.
Adgang til variabler og metoder
Poul Henriksen 9
JAVA programmering/2000
Adgang til variabler og metoder
Ved kald af metode gennem objekt reference
Den aktuelle type af objektet bestemmer, hvilken implementering der
skal bruges
Ved tilgang til en variabel gennem objekt reference
Den erklærede type af reference bestemmer, hvilken variabel der
anvendes.
As previously mentioned, when a subclass overrides a method in a superclass, it hides that method,
not only from a user of the subclass, but from the subclass itself. To avoid having to duplicate code
contained in the hidden method, which is generally undesirable for maintenance reasons, a method
can use the super reference to call the original hidden method in a superclass. The keyword
Noter til
Side 31 af 124
super is similar to this, except that it acts as a reference to the current object as an instance of
its superclass.
Udskiftning af Objekt Referencer
Poul Henriksen
10
JAVA programmering/2000
Udskiftning af Objekt Referencer
Et objekt af en subklasse kan anvendes hvor der
forventes et objekt af superklassen
Man kan tildele et objekt af subklassen til en variabel af superklassen
Man kan overføre et objekt af en subklasse til en metode, hvor der
forventes en reference til et objekt af en superklasse.
public class CarTest {
public void speedTest(Brava b) {
b.getSpeed();
}
public static void main(String[] args) {
CarTest test = new CarTest();
Bravissimo bs = new Bravissimo(2,engine,turbo);
test.speedTest(bs);
}
public class CarTest {
public void speedTest(Brava b) {
b.getSpeed();
}
public static void main(String[] args) {
CarTest test = new CarTest();
Bravissimo bs = new Bravissimo(2,engine,turbo);
test.speedTest(bs);
}
Brava ba = new Bravissimo(2, engine, turbo); // OK
Brava ba = new Bravissimo(2, engine, turbo); // OK
Any object of a subclass can be used where an object of a superclass is expected. This means you
can assign the reference of an object of a subclass to a variable of a superclass, as shown in the first
example on the slide. Here, we assign a reference to a Bravissimo to a variable ba with a
declared type of Brava. This is legal because a Bravissimobject is a type of Brava; it contains
all the instance variables and methods of a Brava class. Note that while an object of a subclass
can be used in place of an object of its superclass, the converse is not true. For example, a Brava
object cannot be used for a Bravissimo object, because a Brava does not have all the instance
variables and methods of a Brava.
You can also pass an object of a subclass to any method that expects a reference to an object of a
superclass, as shown in the second example on the slide. Here, the instance method
speedTest() has a single argument b with a declared type of Brava. When this method is
called by main(), the actual argument is bs, which is a reference to a Bravissimo. Effectively,
bs is assigned to b, so the next statement b.getSpeed() returns the speed of a Bravissimo,
as you would expect.
A more realistic example might be where we have a collection of cars that includes a mix of
Bravas and Bravissimos. We can create an array of Bravas and store either a Brava or a
Bravissimo in any element in the array. For example:
public static void main(String[] args)
{
CarTest test = new CarTest();
Brava[] carFleet = {
new Brava(4, 1400),
new Bravissimo(2, 2000, turbo),
new Brava(4, 1600)
}
// test all cars in the fleet
Noter til
Side 32 af 124
for (int i=0; i < carFleet.length; i++)
test.speedTest(carFleet[i]);
}
Polymorphisme
Poul Henriksen 11
JAVA programmering/2000
Polymorphisme
Den erklærede type og den aktuelle type (run-time type)
af en objekt reference kan være forskellig
Kald af metoder fastlægges ved run time, og bestemmes af den aktuelle
type af objektet
Dette kaldes polymorphi
class Bravissimo
class Bravissimo
class Brava
class Brava
getSpeed()
getSpeed()
b.getSpeed()
Run-time
type may be
Brava or
Bravissimo
Declared
type is
Brava
Stærk type kontrol
Poul Henriksen 12
JAVA programmering/2000
Stærk type kontrol
Java har stærk type kontrol
Checker kompatibilitet ved oversættelse
Skal sikrer mod fejl
Omhandler bl.a.
Parametertyper
Metoders retur type
Tildelinger
Noter til
Side 33 af 124
Final
Poul Henriksen 13
JAVA programmering/2000
Final
Klasser der er erklæret Final kan der ikke
laves
subklasser af
public final class Color {
. . .
}
public final class Color {
. . .
}
En metode kan erklæres Final
En final metode kan ikke blive overridden
- Sikkerhedformål
public final boolean validatePassword(String pwd) {
. . .
}
public final boolean validatePassword(String pwd) {
. . .
}
Classes and methods are made final for two primary reasons: security and optimisation.
If a method is performing some vital function, such as identity validation or authorisation checking,
then it would be a good idea to make it final since you do not want someone overriding that
method such that it does something naughty.
For example, if the validatePassword() method shown above belongs to a class called
SecurityChecker, then you need to guard against someone extending the SecurityChecker class with
a class called Insecurity, and overriding the validatePassword() method so that it always returns
true.The danger is that through polymorphism an Insecurity object could be passed into a method
which expects a SecurityChecker - and when the validatePassword() method is called on that object,
the insecure code would be called in place of the original validatePassword() code.
For this reason a lot of classes in java.net are declared as final.
If an object or method is declared final, the compiler knows that any references to this type used
at runtime cannot be references to subclasses. In order to compile a program using a reference to
this final class, the compiler must know about all that class’ superclasses. Hence, at compile
time, the compiler can determine exactly which method will be called when the reference is used
and hence the created bytecodes can skip a lot of the complexity of determining polymorphically
which method to call. The simplest case of this is that the invocation of the method can be replaced
with the method code itself. This is known as inlining
Noter til
Side 34 af 124
Object klassen
Java supports a single inheritance model - i.e. each subclass can only extend one superclass. Classes
which do not explicitly extend a superclass implicitly extend java.lang.Object Thus
Object is the root of the Java inheritance hierarchy.
The limitation that only a single class can be (directly) inherited may seem restrictive to those used
to a multiple inheritance model. However, single inheritance helps to avoid the confusions inherent
to a multiple inheritance object tree, and encourages programmers to think carefully about their
design strategy. Also, as we shall see in a later chapter, Java Interfaces can be used to introduce
more flexibility into the single inheritance model.
The Object class defines methods which are inherited by all Java classes. These methods include:
clone(), hashCode(), finalize(), equals()
Refer to the Java documentation for details of how these methods work.
Individual classes can override the methods of java.lang.Object to provide class specific
behaviour. The String class overrides equals() to compare the Unicode characters which
form each string's content.
Noter til
Side 35 af 124
Design (is a)
Poul Henriksen
15
JAVA programmering/2000
Arve skal kun anvendes ved ægte
"is a
"
relationsforhold
Det skulle altid være nødvendigt, at erstatte et objekt af en superklasse
med et objekt af en subklasse
Alle metoder I superklassen skal give mening I subklassen
Design
Only use inheritance to model a genuine "is a" relationship. In other words, don't use inheritance
unless all of the inherited methods apply to the subclass. If you can't substitute an object of a
subclass for an object of one of its superclasses, you do not have a genuine "is a" relationship, so do
not try to use inheritance.
Also, if you do use inheritance, exploit the polymorphic nature of the instance methods in the
inheritance hierarchy. For example, if you find that you need to test for the type of object in an
inheritance tree, use polymorphism to avoid having to write separate code to handle objects of each
class. This will maximise the reusability of your code and make your code easier to maintain in the
future.
Design for udvidelser
Poul Henriksen 16
JAVA programmering/2000
Hvordan designes, så det er nemt at udvide ?
Grundregel :
Alle data private
Lav get- og set metoder til alle data
Hjælpemetoder er public
Grænseflade til dem der anvender klassen :
Public metoder + (evt. Public data)
Grænseflade til dem der udvider klassen :
Public og protected metoder + (evt.) data
Design for udvidelser
Noter til
Side 36 af 124
Eksempler på arv
Poul Henriksen
17
JAVA programmering/2000
Eksempel 1
personarv
Eksempel 2
Ansat. Ansatpolymorf
Eksempler på arv
Class Ansat
class Ansat extends Person{
private long loen;
Ansat chef;
Ansat(){
loen = 0;
chef = null;
System.out.println("Ansat oprettet");
}
Ansat(String nytNavn){
this(nytNavn, 15, 0, null);
}
Ansat(String nytNavn,int nyAlder, long loen, Ansat chef){
super(nytNavn,nyAlder);
this.loen = loen;
this.chef = chef;
}
public long getloen(){
return loen;
}
public Ansat getChef(){
return chef;
}
public String toString(){
String var ="nr. " + idNum +" " + getNavn() + " har som ";
if (chef != null)
Noter til
Side 37 af 124
var += " chef " + chef.toString();
return var;
}
protected String print(){
return (super.idNum+ " "+ super.getNavn()+ " " +
super.getAlder()+ " "+ this.getloen());
}
}
class TMC_Ansat{
public static void main(String[] args){
Comparator1 c;
Person ptabel[] = new Person[3];
ptabel[0] = new Ansat("Henrik", 45, 40000,null);
ptabel[2] = new Ansat("Svend", 40, 25000, null);
ptabel[1] = new Ansat("Erik", 30, 15000,null);
for(int i =0;i<ptabel.length;i++){
ptabel[i].udskriv();
}
System.out.println("vælg et nummer: ");
System.out.println("1 IdNum 2 Alder 3 Løn ");
int valg = RHSIo.readInt();
switch(valg){
case 1:c = new Comparator_PersonIdNum();break;
case 2:c = new Comparator_Personalder();break;
case 3:c = new Comparator_Personløn();break;
default:c = new Comparator_PersonIdNum();
}
Sort s = new Sort();
s.bobblesort(c,ptabel,3);
for(int i =0;i<ptabel.length;i++){
ptabel[i].udskriv();
}
//opretter et Object array
Object ltabel[] = new Person[3];
ltabel[0] = new Person("Lasse",36);
ltabel[1] = new Person("Tine",30);
ltabel[2] = new Ansat("Camilla",14, 1000,null);
Sort b = new Sort();
b.bobblesort(c,ltabel,3);
for(int i =0;i<ltabel.length;i++){
((Person)ltabel[i]).udskriv();
}
}
}
Noter til
Side 38 af 124
Kapitel 3 Abstrakte klasser og interfaces
Poul Henriksen
1
JAVA programmering/2000
Abstrakte klasser og interfaces
Design konstruktioner
Bruges til at specificere kontrakten for typen
Ingen instancer af abstrakte klasser eller interfaces
Sikrer, at brugerne af klassen/interfacet overholder kontrakten
Er helt eller delvist amputerede klasser
Klasser kan arve fra en superklasse, men implementere
mange interfaces
When you design a set of classes, it is often a good idea to factor out as much common data and
behaviour as possible into a shared superclass. If this superclass becomes so general or abstract
that it is used only as a framework by subclasses and is never instantiated, that class is known as an
abstract class.
Take cars, for example. There are many types of car, but all cars share similar features so a Car
class would be a obvious candidate for an abstract class. We could place things that are common to
all cars in the Car class. Then, we would derive our concrete (i.e. non-abstract) Astra, Brava,
Corsa, etc classes from the Car class. By law, all cars must have a speedometer, so to ensure that
all concrete (i.e. non-abstract) classes provide a getSpeed() method, we would specify
getSpeed() as an abstract method in the Car class.
A class can be declared as abstract using the abstract keyword as shown in the example on the
slide. It can contain anything a normal class can contain, such as instance variables and instance
methods, plus usually some abstract methods. Note that it is impossible to instantiate an abstract
class.
Noter til
Side 39 af 124
Abstrakte klasser
Poul Henriksen 2
JAVA
programmering/2000
Abstrakte klasser
Abstrakt klasse :
Tilbyder delvis implementation af nogle begreber
Man kan ikke lave instancer af den
Subklasser
Arver en eller flere konkrete metoder
Arver en eller flere abstrakte metoder
En
subklasse må implementere alle abstrakte metoder
der arves fra den abstrakte superklasse
public abstract class Car {
public abstract int getSpeed();
. . .
public abstract class Car {
public abstract int getSpeed();
. . .
public class Brava extends Car {
public int getSpeed() {
return (getRevs() / 100) * gear;
}
public class Brava extends Car {
public int getSpeed() {
return (getRevs() / 100) * gear;
}
When you design a set of classes, it is often a good idea to factor out as much common data and
behaviour as possible into a shared superclass. If this superclass becomes so general or abstract
that it is used only as a framework by subclasses and is never instantiated, that class is known as an
abstract class.
Take cars, for example. There are many types of car, but all cars share similar features so a Car
class would be a obvious candidate for an abstract class. We could place things that are common to
all cars in the Car class. Then, we would derive our concrete (i.e. non-abstract) Astra, Brava,
Corsa, etc classes from the Car class. By law, all cars must have a speedometer, so to ensure that
all concrete (i.e. non-abstract) classes provide a getSpeed() method, we would specify
getSpeed() as an abstract method in the Car class.
A class can be declared as abstract using the abstract keyword as shown in the example on the
slide. It can contain anything a normal class can contain, such as instance variables and instance
methods, plus usually some abstract methods. Note that it is impossible to instantiate an abstract
class.
Noter til
Side 40 af 124
Abstrakte metoder
Poul Henriksen 3
JAVA
programmering/2000
Abstrakte metoder
En abstract metode
er en,
som det ikke giver
mening, at
implementere af en klasse
En generisk operation
Del af en abstract klasse
Skal implementeres af en konkret subklasse
Forskellige subklasser kan implementere metoderne forskelligt
Syntaks:
Abstrakte metoder markeres som abstract og der angives kun
signaturen
Klassen erklæres abstract
public abstract class Car{
public abstract int getSpeed();
. . .
public abstract class Car{
public abstract int getSpeed();
. . .
Note the
semicolon
Polymorfi med abstrakte klasser
Poul Henriksen
4
JAVA programmering/2000
Polymorfi med abstrakte klasser
En samling af forskellige subklasser
Kan kalde enhver af objektets superklasses metoder uden at vide,
hvilken klasse objektet er af.
public abstract class Car {
public abstract int getSpeed();
public abstract class Car {
public abstract int getSpeed();
. . .
Car[] carFleet = {
new Brava(4, 1400),
new Bravissimo(2, 2000, turbo),
new Brava(4, 1600)
};
. . .
// test all cars in fleet
for (int i=0; i < carFleet.length; i++)
carFleet[i].getSpeed();
. . .
. . .
Car[] carFleet = {
new Brava(4, 1400),
new Bravissimo(2, 2000, turbo),
new Brava(4, 1600)
};
. . .
// test all cars in fleet
for (int i=0; i < carFleet.length; i++)
carFleet[i].getSpeed();
. . .
As shown on the slide, we can create an array of Cars and store a reference to either a Brava or a
Bravissimo in any element in the array. Then, we can call a method of any object in the array
without knowing its precise class. Even if the implementation of the method is different for each
subclass (as in the case of getSpeed()), the correct method will be invoked. As mentioned
previously, this behaviour is called polymorphism.
Noter til
Side 41 af 124
Interfaces
An interface is similar to a abstract class, except that it cannot have any concrete methods or
instance variables. In other words, it is simply a collection of abstract methods and/or constants.
Any class that implements an interface must implement all of the methods specified in that
interface. Otherwise, it must be declared abstract.
Note that the name of an interface is often an adjective such as Steerable, Traceable,
Sortable, etc, whereas the name of a class is usually a noun such as Car, BankAccount, Order,
Event, etc.. The core Java packages include a number of standard interfaces such as Runnable,
Cloneable, ImageObserver, ActionListener, etc. We will discuss the use of some of
these standard interfaces later in the course.
Definering af et Interface
Poul Henriksen 6
JAVA programmering/2000
Definering af et Interface
I en interface definition:
Brug
keyword interface istedet for class
Alle metoder er implicit public og abstract
Alle variabler er
implicit
final, public og static (dvs. konstanter)
Enhver klasse der implements et interface skal
implementere alle metoder specificeret i interfacet
public interface Steerable
{
void turnLeft(int deg);
void turnRight(int deg);
}
public interface Steerable
{
void turnLeft(int deg);
void turnRight(int deg);
}
Noter til
Side 42 af 124
As shown on the slide, an interface is defined using the keyword interface. All methods
specified in an interface are implicitly public and abstract. Any variables specified in an
interface are implicitly public, static and final (i.e. constants).
Implementering af et Interface
Poul Henriksen 7
JAVA programmering/2000
Implementing af et interface
Brug keyword implements
Oprems de interfaces der implementeres adskilt med kommaer
public interface Steerable
{
void turnLeft(int deg);
void turnRight(int deg);
public interface Steerable
{
void turnLeft(int deg);
void turnRight(int deg);
public abstract class Car implements Steerable
{
. . .
public void turnLeft(int deg) {
. . .
}
public void turnRight(int deg) {
. . .
}
. . .
public abstract class Car implements Steerable
{
. . .
public void turnLeft(int deg) {
. . .
}
public void turnRight(int deg) {
. . .
}
. . .
Both concrete and abstract classes can implement an interface, but a concrete class must implement
all the methods defined in the interface.
A class specifies that it implements an interface using the keyword implements, as shown on the
slide. A class can also implement more than one interface by specifying a list of interfaces,
separated by commas. For example:
public class Car implements Steerable, Convertible {
. . .
}
If a class cannot implement one or more of the methods specified, it must be declared abstract.
Note that any class can implement an interface, regardless of whether its superclass does or not.
Noter til
Side 43 af 124
Polymorfi
Poul Henriksen 8
JAVA
programmering/2000
Polymorfi
Et interface definerer
en ny
data type (tilsvarende en
klasse definition)
Hvis en metode har et argument af en interfacetype, kan der overføres
en reference til et objekt af en hvilken som helst klasse, som
implementerer det specificerede interface.
public abstract class Car
implements Steerable
{
public void turnLeft(int deg) {
. . .
public abstract class Car
implements Steerable {
public void turnLeft(int deg) {
. . .
. . .
navigate(Steerable s) {
s.turnLeft(90);
. . .
}
. . .
navigate(Steerable s) {
s.turnLeft(90);
. . .
}
Remember that an object reference has a type, and that type may be either a class or an interface. If
it is a class, the reference may refer to an object of that class or any of its subclasses. If it is an
interface, the reference may refer to an object of any class that implements the interface.
Eksempler på Interfaces
Poul Henriksen 9
JAVA programmering/2000
Eksempler på interfaces
Eksempel 1
Opgave Sort (boblesort)
Eksempel 2
Stack Interface
Eksempel 3
Interface LookUp
Eksempel 4
Opgave interface
Noter til
Side 44 af 124
Eksempel Bobblesort
interface Comparator{
public int compare(Object o1, Object o2);
}
interface Comparator1 extends Comparator{
public int compare(Person P1, Person P2);
}
public class Sort{
public Person[] bobblesort(Person[] T, int n){
int i,j;
Person temp;
for (i = 0; i< n;i++)
for (j = i;j < n ; j++){
if (T[i].idNum < T[j].idNum){
temp = T[j];
T[j] = T[i];
T[i] = temp;
}
}
return T;
}
public void bobblesort(Comparator1 c, Person[] T, int number){
int i,j;
Person temp;
for (i = 0; i< number;i++)
for (j = i;j < number ; j++){
if (c.compare(T[i], T[j])== -1){
temp = T[j];
T[j] = T[i];
T[i] = temp;
}
}
}
public void bobblesort(Comparator1 c, Object[] T, int number){
int i,j;
Object temp;
for (i = 0; i< number;i++)
for (j = i;j < number ; j++){
if (c.compare(T[i], T[j])== -1){
temp = T[j];
Noter til
Side 45 af 124
T[j] = T[i];
T[i] = temp;
}
}
}
}
Eksempel Interface Lookup
interface Lookup
{
Object find(String name);
}
interface EditableLookup extends Lookup
{
boolean add(String addName, Object Val);
boolean remove(String name);
}
class SimpleLookup implements Lookup
{
private String[] Names;
private Object[] Values;
public Object find(String name)
{
for( int i= 0; i < Names.length; i++)
{
if (Names[i].equals(name) )
return Values[i];
}
return null;
}
}
class SimpleEditableLookup implements EditableLookup
{
private String[] Names;
private Object[] Values;
private final int MaxInt;
private int næsteFrieplads = 0;
public SimpleEditableLookup(int Max)
{
MaxInt = Max;
Names = new String[MaxInt];
Values = new Object[MaxInt];
}
public Object find(String name)
{
for( int i= 0; i < Names.length; i++)
{
if (Names[i].equals(name) )
return Values[i];
}
Noter til
Side 46 af 124
return null;
}
public boolean add(String addName, Object Val)
//ingen check for dubletter
{
if ( næsteFrieplads<MaxInt )
{
Names[næsteFrieplads] = addName;
Values[næsteFrieplads] = Val;
næsteFrieplads++;
return true;
}
else
return false;
}
public boolean remove(String name)
{
for(int i = 0; i <næsteFrieplads; i++)
{
if ( Names[i].equals(name) )
{
Names[i] = null; //hul i listen
Values[i] = null;
return true;
}
}
return false;
}
public String toString()
{
String str = "";
for(int i = 0; i<næsteFrieplads; i++)
{
str = str + Names[i] + " = " + Values[i] +
"\n";
}
return str;
}
}
class Test
{
public static void main(String[] args)
{
SimpleEditableLookup s = new SimpleEditableLookup(5);
s. add("Første" , "en tekststreng");
s.add("Anden", new Integer(100) );
System.out.println(s);
s.remove("Første");
System.out.println(s);
}
}
Noter til
Side 47 af 124
Kapitel 4 String klassen
Poul Henriksen 1
JAVA programmering/2000
String
klassen
Repræsenterer
en
sekvens af
Unicode
karakterer
Kan ikke ændres fast længde og read-
only
En String
er ikke det samme som
et array af karakterer
Kan skabes indirekte
...
Eller ved
at bruge
+
eller +=
til
at
sammensætte
to
strenge
Kan kopiere
en
eksisterende streng ved at
bruge
new
String model = "Audi”;
String model = "Audi”;
int
number = 323;
String model = "BMW " + number + "i”;
int
number = 323;
String model = "BMW " + number + "i”;
public Car(String make) {
String model = new String(make);
. . .
public Car(String make) {
String model = new String(make);
. . .
Ever since you started this course, you have been using strings, which are simply sequences of
Unicode characters such as "Hello". Unicode is an international standard for defining characters (in
any written language) in a 16-bit character set.
Although Java does not have a primitive string type, the language does provide some built-in
support for creating strings (using double quotes) and concatenating strings (using the + and +=
operators). Additional support for creating and accessing strings is provided by the methods of the
predefined String class.
The String class represents an immutable string, that is, a sequence of characters that are of a
fixed length and are read-only. Support for mutable strings is provided by the StringBuffer
class.
As shown on the slide, you can create a new string in three ways:
Implicitly by enclosing a string in double quotes
Using the + or += operators
Using the new operator
Note that the String class provides the following constructors:
String() creates an empty string with the value ""
String(String value) creates a copy of the specified String object value
Noter til
Side 48 af 124
Udvalgte String metoder
Poul Henriksen 2
JAVA
programmering
/2000
Udvalgte
String
metoder
length() returnerer antal karakterer
I
strengen
charAt()
returnerer en
char
den
specificerede
position
Første karakter
I en string
har position 0
equals() returnerer true hvis to strings er identiske
Brug ikke
==
operatoren
.
Sámmenligner
memory addresser
compareTo()sammenligner to strings og returnerer
en int
0
hvis lig
den specificerede streng
Negative hvis mindre end den specificerede streng
Positive
hvis større
end den
specificerede streng
if (model.charAt
(model.length()
-
1) == 'i')
streetCred += 20;
if (model.charAt(model.length()- 1) == 'i')
streetCred += 20;
if (model.equals("Golf
GTi"))
streetCred
+= 20;
if (model.equals("Golf
GTi
"))
streetCred += 20;
The String class provides some useful methods. For example:
length() returns the number of characters in the string
charAt() returns the character at a specified position in the string
startsWith() returns true if string (or specified substring) starts with specified prefix
endsWith() returns true if string ends with specified suffix
substring() returns a new string which is a specified subset of the string
toUpperCase() returns a new string with each character converted to upper case
toLowerCase() returns a new string with each character converted to lower case
trim() returns a new string with any leading or trailing white-space removed
When using charAt(), substring() and similar methods, note that the first character in the
string is at position 0 (like C and C++). As mentioned previously, you cannot change individual
characters in a string. Instead, you must create a new string (e.g. using substring() and the +
operator) or use the StringBuffer class.
The String class provides several methods to compare strings:
equals() returns true if specified string is identical
equalsIgnoreCase() is similar to equals() except that it ignores case
compareTo() is useful for ordering two or more strings (in Unicode numerical order)
Do not attempt to use the == operator to see whether two strings are equal, because it will only
return true if two strings have the same reference, i.e. they are stored in the same location, and
you cannot guarantee that this will be so (the == operator is not overloaded as in C++) . Also, note
that in JDK 1.02, compareTo() does not fully address the localisation issues of Unicode.
Noter til
Side 49 af 124
toString() metoden
Poul Henriksen 3
JAVA
programmering/2000
toString() metoden
En klasse kan have en public toString() metode
Kaldes automatisk hvis et objekt af klassen er
specificeret i et udtryk, hvor der forventes en string
public class Car {
private String model;
private numDoors = 4;
public String toString() {
return numDoors + " door " + model;
}
}
public class Car {
private String model;
private numDoors = 4;
public String toString() {
return numDoors + " door " + model;
}
}
Car myCar = new Car("Cavalier", 5);
. . .
System.out.println("My car is a " + myCar);
Car myCar = new Car("Cavalier", 5);
. . .
System.out.println("My car is a " +
myCar
);
If a class provides a public toString() method that returns a String object, that method is
invoked whenever that object of that class is used in an expression where a String is expected,
for example, on one side of a + or += operator. If a toString() method is not defined in a class,
it inherits one from the Object class, which simply returns a string representation of its type (i.e.
its primitive type or its class name concatenated with a hash code). Note that if a null reference is
converted to a string, the result is "null".
StringBuffer klassen
Poul Henriksen 4
JAVA programmering/2000
StringBuffer klassen
Lig String klassen, dog kan StringBuffer objekter
ændres
Tilbyder ekstra metoder, som eks. insert() og append()
Anvendelige til at opbygge og modificere tekst strenge
Arver ikke fra string (String er fianl)
public String reverseIt(String s) {
StringBuffer sb = new StringBuffer();
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
public String reverseIt(String s) {
StringBuffer sb = new StringBuffer();
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
Although it is unrelated, the StringBuffer class provides the same methods as the String class.
However, unlike the String class, the StringBuffer class represents strings that can be
modified at run-time, so it is much more useful for manipulating strings. For example, the
StringBuffer class provides some additional methods, including:
Noter til
Side 50 af 124
setCharAt() changes the character at the specified position in the string buffer
setLength() truncates or extends the string buffer to the specified length
append() adds characters to the end of the string buffer and returns the string buffer
insert() inserts characters at specified position in the string buffer
The slide shows how you might use the StringBuffer class to reverse the characters in a string.
Wrapper klasser
Poul Henriksen 5
JAVA
programmering/2000
Wrapper klasser
Java
tilbyder wrapper
klasser til at repræsentere alle
primitive
typer
Integer for ints, Float for floats, Boolean for booleans, osv
.
Gør det muligt, at konvertere primitive typer til objekter
Tilbyder nogle instance
metoder f.eks.
intValue
()
, floatValue
(), osv
.
Indeholder også flere klasse metoder f.
eks.
Integer.toString() og Integer.parseInt()
... og konstanter f.eks.
Integer.MIN_VALUE og
Integer.MAX_VALUE
int vote = 23578;
Integer
voteObject = new Integer(vote);
. . .
int
vote = 23578;
Integer voteObject
= new Integer(vote);
. . .
.
String konvertering
Poul Henriksen 6
JAVA programmering/2000
String konvertering
For at konvertere et String objekt til en int, brug
Integer.parseInt()
For at konvertere et Integer object til en String, brug
Integer.toString()
public class Average {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: Average <list>");
System.exit(1);
}
float sum = 0;
for (int i=0; i<args.length; i++)
sum += Integer.parseInt(args[i]);
System.out.println("Average is " +
sum / args.length);
}
public class Average {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: Average <list>");
System.exit(1);
}
float sum = 0;
for (int i=0; i<args.length; i++)
sum += Integer.parseInt(args[i]);
System.out.println("Average is " +
sum / args.length);
}
Each wrapper class provides some useful conversion methods. For example, the Integer class
provides a class method, parseInt(), which converts the Unicode string representation of an
integer value into an int primitive type. As shown on the slide, this method is typically used in a
Noter til
Side 51 af 124
main() method to convert command-line arguments, which are always passed as strings, into
primitive types.
Note that it is the type being converted to that provides the conversion method. Also, there is no
Float.parseFloat() method. Instead, you must use the following (rather clumsy)
construction:
new Float(String).floatValue()
Eksempler
Poul Henriksen 7
JAVA programmering/2000
Eksempler
StringSammenligning
StringLen
RelatedStrings
StringKonvertering
StringBufferUtil
Se udleverede eksempler om String.
Noter til
Side 52 af 124
Kapitel 5 Exceptions
Poul Henriksen JAVA programmering 1
Exceptions
Mange fejl kan opstå ved program afvikling
Kodefejl : division med 0, fejlindeksering af tabel
Fejl i tilsluttede enheder : printer off line, fejl i
netværkskort
Systemfejl : out of memory
Fejlbehandling :
Traditionelt : API funktioner returnerer fejlkoder og
test efter hvert kald i ex. if
-
sætninger
Alternativt : brug exceptions til fejlhåndtering
If an Error is generated, it normally indicates a problem that will be fatal to the program.
Examples of this type of error are running out of memory or being unable to load a class.
Obviously, these could be handled by complex programming; however, a small program, such as a
Java class, will normally find this sort of thing outside its scope.
Exceptions are split into two types: those that derive from RuntimeException and those
that do not. This is slightly misleading, since all exceptions occur at runtime. However, a useful
rule of thumb is that a runtime exception is caused due to a programming error that could have been
avoided, e.g. divide by zero, array bounds exceeded.
Other exceptions are generated due to problems beyond the programmer’s control. An example
would be creating a URL object. The constructor takes a string URL of the form
“http://www.qatraining.com” or “ftp://ftp.microsoft.com”. It would be difficult for the programmer
to determine beforehand whether the string URL is correct or not since that depends on which
network classes are currently available. In these cases, the method in which the exception is
generated will indicate the possibility that it might throw a particular exception.
Noter til
Side 53 af 124
Fejlbehandling vha. exceptions
Poul Henriksen JAVA programmering
2
Fejlbehandling vha. exceptions
API funktioner smider
exceptions
Hvis exception forekommer søges der efter
en passende exception handler
Hvis handler findes overføres kontrol til
handler
Ellers, fejl rapporteres og program terminerer
En mere robust teknik til håndtering af fejl
Java og exceptions
Poul Henriksen JAVA programmering 3
Java og exceptions
Java API kaster exceptions
For at ”catch” en exception placeres koden i en ”try
blok, som har en eller flere ”
catch” sætninger
Hvis exception forekommer søges der automatisk
efter en ”catch
” der matcher exception
Hvis encatch” matcher overføres kontrol til denne
exception handler
Kan udbedre fejlen
Kan rydde op og smide
exception videre
Noter til
Side 54 af 124
Simpelt eksempel på try og catch
Poul Henriksen JAVA programmering 4
Simplet eksempel
try {
// Code that may throw an I/O exception
b = stream1.read();
b = stream2.read();
b = stream3.read();
} catch ( IOException e ) {
// Handle the exception
}
try {
// Code that may throw an I/O exception
b = stream1.read();
b = stream2.read();
b = stream3.read();
} catch ( IOException e ) {
// Handle the exception
}
I/O Exception
transfers
control
Throwable
Poul Henriksen JAVA programmering 5
Throwable
Alle errors og exceptions arver fra klassen Throwable
Der er to typer af Throwable objects
Errors er unormale forhold
Betragtes som fejl der ikke kan udbedres
Skal ikke forsøge at opfange dem
Exceptions
Unormale forhold, som man kan komme udbedre virkningne af
To typer af Exceptions
Checked exceptions
Der er intet galt med programmet, men noget uventet har indtruffet
Disse skal opsamles og behandles ellers vil programmet ikke oversætte
Runtime exceptions
Fejl I programkodningen
Ikke nødvendigt, at checke for
Noter til
Side 55 af 124
Eksempler på fejl
Poul Henriksen JAVA programmering
6
Eksempler på fejl
Errors
OutOfMemoryError
InternalError (
Fejl i Java Virtual Machine)
NoSuchMethodError (Hvis klassen er ændret mellem
compilerings- og afviklingstidspunktet
)
Runtime exceptions
ArrayIndexOutOfBoundsException
ArithmeticException
Andre (checked) exceptions
MalformedURLException
IOException
ClassNotFoundException
The above slide gives examples of possible errors and exceptions that you will encounter. It is not
an exhaustive list by any means. All of these will be found on a Java hierarchy chart as subclasses
of Throwable.
Opsamling af exceptions (catch)
Poul Henriksen JAVA programmering 7
Opsamling af exceptions (catch)
Default exception håndtering
Afslutning af metoden, hvor exception blev kastet
Når metoden returnerer vil den aktuelle kontekst blive nedlagt indtil exception
opfanges
Hvis exception ikke opfanges, vil applikationen terminere
Exceptions kan opfanges med en catch sætning
Modtager af exception kan
:
opfange og behandle exception
Opfang og send videre I nyt navn
Sende exception ubehandlet videre
Der kan forekomme mange catch sætninger til at opfange mange typer
exceptions
try {
URL u = new URL("http://www.qatraining.com");
} catch (MalformedURLException e) {
System.err.
println("Couldn't open URL: " + e);
}
try {
URL u = new URL("http://www.qatraining.com");
} catch (MalformedURLException
e) {
System.err.println("Couldn't open URL: " + e);
}
If your code can throw multiple exceptions which derive from the same parent, then you need only
catch the parent exception. For example, if your code can throw either a
FileNotFoundException or an EOFException, then you only need to catch
IOException. This obviously loses some detail about the exact problem, but it requires less code
and complexity.
If you cannot do anything useful with an exception, the general rule is not to catch it. If the
exception is not caught, it will eventually result in a stack trace which is useful for debugging
purposes. Handling exceptions badly can throw the debugging programmer off the scent of the real
problem.
Noter til
Side 56 af 124
If a catch or finally clause clause throws another exception, the catch clauses of the try
clause are not re-examined. Such exceptions can be caught only by an outer try body.
Finally
Poul Henriksen JAVA programmering 8
Finally
finally sætningen kan garantere at en blok af sætninger altid vil blive
afviklet
Kan bruges alene eller sammen med en eller flere catch sætninger
Hvis try blokken forlades pga. ...
Ved at passere forbi slut }
Der forekommer en return eller break sætning
En exception blev kastet
. . . Kontrollen overføres til finally
FileInputStream fin = null; int b = 0;
. . .
try {
fin = new FileInputStream(file);
while ((b = fin.read()) != -1)
if (b < 0x20 || b > 0x7f) return;
} finally {
fin.close(); //clean up - but will this work?
}
FileInputStream fin = null; int b = 0;
. . .
try {
fin = new FileInputStream(file);
while ((b = fin.read()) != -1)
if (b < 0x20 || b > 0x7f) return;
} finally {
fin.close(); //clean up - but will this work?
}
The finally block will always be executed, even if the try or catch blocks are exited with a
break, continue or return. This is very useful for cleaning up some resource, such as a file,
that a method has acquired.
Note though, that the close() method on the slide also generated checked exceptions - so more
try / catch blocks will be required!
Et samlet eksempel
Poul Henriksen JAVA programmering 9
Et samlet eksempel
String host = "www.qatraining.com";
URL u;
void makeConnection() {
try
{
u = new URL("http://" + host);
}
catch (MalformedURLException e)
{
System.out.println("Can't contact http//" + host);
return;
}
finally
{
System.out.println("This will always be done");
}
System.out.println("Only see this if successful");
}
String host = "www.qatraining.com";
URL u;
void makeConnection() {
try
{
u = new URL("http://" + host);
}
catch (MalformedURLException e)
{
System.out.println("Can't contact http//" + host);
return;
}
finally
{
System.out.println("This will always be done");
}
System.out.println("Only see this if successful");
}
If this code executes without causing an exception, the following messages will be printed:
This will always be done
Only see this if successful
Noter til
Side 57 af 124
If the URL constructor throws an exception, the following messages will be printed:
Can’t contact http://www.qatraining.com
This will always be done
Erklærede exceptions
Poul Henriksen JAVA programmering 10
Erklærede exceptions
Nogle metoder kan kaste exceptions
Fremgår af API dokumentation,
public URL(String spec) throws
MalformedURLException
Programmet skal håndtere erklærede exceptions en eller anden måde,
ellers kan det ikke oversættes
Nogle metoder kan kaste
mere end en exception
// This does not compile!
public class MyClass {
...
public URL getURL() {
URL u = new URL("http://www.qatraining
.com");
return u;
}
}
// This does not compile!
public class MyClass {
...
public URL getURL() {
URL u = new URL("http://www.qatraining.com");
return u;
}
}
requires try / catch block
In James Gosling and Ken Arnold’s book The Java Programming Language, it states “Experience
has shown that programmers forget to handle errors, or defer handling them until some coding
future that never arrives”. The compiler-enforced handling of declared errors removes this
possibility.
If your method can throw multiple exceptions which all derive from the same parent, then rather
than declaring each exception separately, you can just declare the parent class. This reduces the
amount of code required but is not as useful for a programmer using your class. It is best practice to
formally document all the exceptions your method throws in its declaration.
If a method throws multiple exceptions, the possible exceptions are listed after the throws
keyword with comma separators.
Noter til
Side 58 af 124
Passing the Buck
Poul Henriksen JAVA programmering
11
Passing the Buck
Man behøver ikke at behandle en exception
Den kan sendes videre ved at
erklære
, at min metode
throws den exception
der kastes af den
metode der kaldes
Den kaldende metode skal nu behandle denne exception
// This does compile!
public class MyClass {
...
public URL getURL() throws MalformedURLException
{
URL u = new URL("http://www.qatraining
.com");
return u;
}
// This does compile!
public class MyClass
{
...
public URL getURL() throws MalformedURLException {
URL u = new URL("http://www.qatraining.com");
return u;
}
// This does not compile!
public class Test {
...
public static void main(String[] args
) {
MyClass mc
= new MyClass
();
URL u = mc.getURL();
}
}
// This does not compile!
public class Test {
...
public static void main(String[] args) {
MyClass mc
= new MyClass
();
URL u = mc.getURL();
}
}
requires try / catch block
no try / catch block
needed
If you cannot meaningfully handle and exception, or you choose not to, it can be passed back to the
code which called your method. If you state that your method throws a particular exception, you
are not required to handle it within your method. The responsibility now passes to the code which
calls your method.
As you can see from this, somebody must handle the exception. All you are doing is making sure
that it is not you. You should not use this as a general way to force complexity onto your calling
methods.
If your method throws multiple exceptions, the possible exceptions should be listed after the
throws keyword with comma separators.
Behandling af exception i kaldte metoder
Poul Henriksen JAVA programmering 12
Behandling af exception I kaldte metode
Hvis metoden selv behandler exception, er det ikke nødvendigt, at erklære den
// This does compile!
public class MyClass {
public URL changeURL(URL oldURL) {
try {
URL u = new URL("http://www.qatraining.com");
return(u);
} catch (MalformedURLException e) {
return oldURL;
}
}
}
// This does compile!
public class MyClass {
public URL changeURL(URL oldURL) {
try {
URL u = new URL("http://www.qatraining.com");
return(u);
} catch (MalformedURLException e) {
return oldURL;
}
}
}
// This also compiles!
public class Test {
public static void main(String[] args) {
MyClass mc = new MyClass();
URL u2 = mc.changeURL(u1);
}
}
// This also compiles!
public class Test {
public static void main(String[] args) {
MyClass mc = new MyClass();
URL u2 = mc.changeURL(u1);
}
}
If it makes sense to handle an exception there and then in your method then you should do so. The
fewer impositions your method makes on the people who use it, the better. In this case, the code
calling your method does not need to know anything about the exception that you have caught.
Noter til
Side 59 af 124
Exceptions og overriding
Poul Henriksen JAVA programmering
13
Exceptions og overriding
Hvis du overrider metoder, som kaster
exceptions:
Barnets metode der overrider en
metode I
forælder kan
kun throw checked
exceptions erklæret i throws sætning af forældrens overriddet metode
Nye metoder kan kaste færre exceptions end I den metode der overrides
// overridden method in superclass:
public void errorProne() throws InterruptedException,
IOException
{ . . . }
// overridden method in superclass:
public void errorProne() throws InterruptedException,
IOException
{ . . . }
// overriding method in subclass:
public void errorProne
() throws MalformedURLException
,
SQLException
{ . . .}
// overriding method in subclass:
public void errorProne() throws
MalformedURLException
,
SQLException
{ . . .}
MalformedURLException is a subclass of IOException
If you override a method which can throw exception, you do not need to throw all the exceptions
which were declared as thrown by the overridden method. However, you cannot add new types of
exceptions which were not thrown by the superclass method.
Thus in the example on the slide, the errorProne() method of the subclass can omit to declare
itself as throwing InterruptedException, and can declare itself as throwing
MalformedURLException because this error is a subclass of IOException. However, the
new method cannot introduce the SQLException class.
Why should this be so? The answer lies in polymorphism.
If the parent class is named ParentErrorThrower and the subclass is named ChildErrorThrower then
consider the following piece of code:
public void errorTester(ParentErrorThrower pet)
{
try{
pet.errorProne();
}
catch(IOException){ . . .}
catch(InterruptedException){ . . .}
}
Given the declaration of errorProne() in the ParentErrorThrower class this code should
compile correctly. But if the compiler has permitted us to declare the ChildErrorThrower's
errorProne() method as throwing SQLExceptions, what would happen if we passed an
instance of ChildErrorThrower to the errorTester() method? Any SQLExceptions
would not be caught. To guard against such situations, the compiler enforces a policy such that an
overriding method cannot throw a new class of exception.
Noter til
Side 60 af 124
Bruger definerede exceptions
Poul Henriksen JAVA programmering
14
Bruger definerede exceptions
Man kan definere sine egne exceptions
De skal være subklasse af Exception
eller en
af
dens subklasser
Tilføj instance variabler til at indeholde brugbar information om fejlen
Standard exception exception klasser har
to constructors
NewException() default
NewException(string) string indeholder info om fejlen
public class NewException extends Exception {
private Connection c;
public NewException() { super(); }
public NewException(String s) { super(s); }
public NewException(Connection badConn) { c = badConn };
public Connection getTheBadConnection() {
return c; // Caller can examine this to see
} // precisely what went wrong
}
public class NewException extends Exception {
private Connection c;
public NewException
() { super(); }
public NewException(String s) { super(s); }
public NewException(Connection badConn) { c = badConn };
public Connection getTheBadConnection() {
return c; // Caller can examine this to see
} // precisely what went wrong
}
The Exception class is itself a subclass of Throwable. Strictly speaking, you can throw and
catch anything that derives from Throwable. However, it is not common practice to subclass
either Error or RuntimeException.
You may want to define a new exception if there is a specific type of error or combination of errors
that you wish to inform higher-level code about. Since exceptions are caught by type, it may be
important to have a separate type. Also, you may want your exception to hold useful data about the
problem encountered. By defining your own exception, you can store and retrieve this information.
Throwing Exceptions
Poul Henriksen JAVA programmering 15
Throwing Exceptions
Man kaster exceptions med throw”
Det kan være egne eller pre-definerede exceptions
En exception er et object
Man lave en ny instance af en exception hvis man vil kaste den
public void TestExceptions() {
try {
throw new NewException(“Ooops”);
} catch (NewException e) {
System.err.println(“Got my exception :” + e);
}
}
public void TestExceptions() {
try {
throw new NewException(“Ooops”);
} catch (NewException e) {
System.err.println(“Got my exception :” + e);
}
}
public void myFunc(int i) throws NewException {
if (i < 10) {
// Process file - this may give an error
throw new NewException(file);
}
else
throw new NewException(“Pass this down”);
}
public void myFunc(int i) throws NewException {
if (i < 10) {
// Process file - this may give an error
throw new NewException(file);
}
else
throw new NewException(“Pass this down”);
}
new
You may wish to indicate errors yourself by throwing exceptions when you encounter a problem.
The exceptions that you throw can be standard system exceptions or those of your own making.
The main thing to remember about throwing an exception is that you are actually throwing a
throwable object. As such, it needs to be instantiated before use, just like any other object.
Noter til
Side 61 af 124
Be careful to ensure that your exception throwing does not leave any code unreachable. If this is
the case, the code will not compile.
Information om exceptions
If you pass the caught exception to an output method like println(), it will tell you both the
class of the exception and also the contents of any string passed when the exception’s constructor
was called. The same information is returned from the exception’s toString() method.
If you know what the exception is and only want the detailed information passed to the constructor,
then use the getMessage() method, which returns the string message passed to its constructor.
Another useful method of Throwable is printStackTrace().
Større eksempler
Poul Henriksen JAVA programmering 17
Større eksempler
Eksempel 1
Class Fil
Eksempel 2
StackInterface
Noter til
Side 62 af 124
Eksempel på exceptions
public class FullStackException extends Exception{
public FullStackException(){
super("stakken er fuld");
}
}
import FullStackException;
public class stack{
private int[] tal;
private int top;
private int max;
public stack(){}
public stack(int max){
tal = new int[max];
top = 0;
this.max=max;
}
public void push(int ny)
throws FullStackException{
if(full())
throw new FullStackException();
tal[top] = ny;
top++;
}
public int pop()
throws EmptyStackException{
if(empty())
throw new EmptyStackException();
top--;
return tal[top];
}
public boolean empty(){
if(top == 0)
return true;
else
return false;
}
public boolean full(){
if(top == max)
return true;
else
return false;
}
Noter til
Side 63 af 124
public void print(){
System.out.println("det naeste tal i stakken er ");
}
}
import rhs.*;
class TMC_stack{
public static void main(String[] args){
New_Stack liste = new New_Stack(20);
for(int i =0;i<22;i++){
try{
liste.push(i);
liste.tæl_push();
}catch(FullStackException e){System.out.println(e);}
}
System.out.println("Der er sat " +liste.hent_antal_push()+ " tal på stakken");
for(int i =0;i<22;i++){
RHSIo.readChar();
liste.print();
try{
System.out.print(liste.pop());
}catch(EmptyStackException a){System.out.println(a);}
}
}
}
Noter til
Side 64 af 124
Kapitel 6 Packages
Poul Henriksen
1
JAVA programmering
Packages
Package =
Samling af relaterede klassser, interfaces og sub-packages
Motivation
Gruppering
Relaterede klasser sammenholdes
Namespace
Navne på klasser skal kun være entydige inden for en package
Beskyttelse
Kun public klasser og interfaces kan ses ude fra
Implementeringsdetaljer skjules
Let at ændre
Source files for classes must be placed in files with the extension .java. These are normally held
one class per file, and the filename (excluding the extension) must be the same as the name of the
class. (Case is sensitive.) Thus the file Car.java must contain the class Car. Other classes may
also be placed in this file, but these must not be public classes; they may only be supporting classes
used internally inside this package and unable to be used outside the package(see following pages).
In other words, only one class in a source file may be public, and the rest must be default. The
public class provides the filename. A public class is one which can be used anywhere, whereas the
default classes, can only be used in this package.
Classes are compiled into .class files, one per class, with the classname providing the filename.
Package opbygning
Poul Henriksen
2
JAVA programmering
Package opbygning
En package identificerer hvor klassens kode kan findes
Packages er hierarkisk organiseret
Mapper til en hierarkisk filstruktur
Standard med omvendt internet domænenavn
com.qatraining.cad.vehicle
Car
Engine Truck
Gearbox
com
qatraining
cad
vehicle
Car.class
Engine.class
Truck.class
Gearbox.class
Noter til
Side 65 af 124
Packages are a means of organising classes into groups - which is vital in a system which contains a
large number of classes.
Packages organize class names using a simple hierarchical structure which must map directly onto
the location of the corresponding class files in a directory structure. Thus when one knows the full
and with which other classes it has been grouped. If your package structure has been named
informatively, you should also gain some knowledge about the function of the classes it contains.
Each package has two distinct sets of classes: those which are available to all users, and those
which are hidden inside the package. Classes are usually hidden within a package when they merely
provide low-level implementational details to assist the functioning of a publicly available class.
Referering til klasser i en package
Poul Henriksen
3
JAVA programmering
Referering til klasser I en package
Klassenavnet inklusive package navnet kan være meget
langt
import sætninger gør det muligt, at anvende forkortede
navne
Hvis der er navnesammenfald mellem klasser I to
packages
Anvendes det fulde navn på klassen. For at undgå tvetydigheder
Pakken java.lang importeres implicit
Alle klasse navne heri kan anvendes uden at kvalificere det med
package navne
com.qatraining.cad.vehicle.Car car1; // yeuch
vehicle.Car car1; // better
Car car1; // excellent
com.qatraining.cad.vehicle.Car car1; // yeuch
vehicle.Car car1; // better
Car car1; // excellent
The full name of a class includes its package - for example the full name for the Button class is
java.awt.Button. Full class names are lengthy and inconvenient to use; but by using import
statements one can refer to a class using its abbreviated name (i.e. its class name minus its package
structure).
Each import statement specifies a package name; this has the effect of allowing the classes in
that package to be specified in their abbreviated form. This has to be done with a little care to
ensure that the abbreviated versions of class names do not clash.
Import statements must appear at the beginning of a file (but after the package statement if one is
present). Each file can contain many imports.
Note that the import statement does not load classes into memory - it simply allows classes to be
specified with an abbreviated name.
Noter til
Side 66 af 124
Importering af klasser
Poul Henriksen
4
JAVA programmering
Importering af klasser
Import
sætningen importerer klasser
For at importere en klasse I en package:
import com.qatraining.cad.vehicle.Car; // class
. . .
Car car1; // can use shortened name
import com.
qatraining.cad.vehicle.Car; // class
. . .
Car car1; // can use shortened name
import com.qatraining.cad.vehicle.*; // wildclass
. . .
Car car1; // can use shortened name
Truck t; // for all classes in package
import com.qatraining.cad.vehicle.*; // wildclass
. . .
Car car1; // can use shortened name
Truck t; // for all classes in package
For at importerer alle klasser i en pakke
:
Alternativt : brug fuldt kvalificerende navne
The first form of import statement shown on the slide specifies a single class (Car), and allows
only that specific class to be referred to by its abbreviated name.
The second form of import is more useful - it allows any (public) class in the package to be
specified by its abbreviated name. This may occasionally result in name clashes, where classes in
the imported package have the same name as other classes in other imported packages. If problems
arise try the first form instead.
Placering af package
Poul Henriksen
5
JAVA programmering
Placering af Package
Pakken og dens klasser skal placeres I en filstruktur der
er mappet udfra navnet og pakken
Relativ til det aktuelle katalog og CLASSPATH
CLASSPATH bruges af compileren og den Virtuelle
Maskine til at finde klasserne
Hvis en klasse ikke er korrekt placeret forekommer en fejl
com.qatraining.cad.vehicle
com.qatraining.cad.vehicle
.\com\qatraining\cad\vehicle
\classes\com\qatraining\cad\vehicle
\usr\des\com\qatraining\cad\vehicle
.\com\qatraining\cad\vehicle
\classes\com\qatraining\cad\vehicle
\usr\des\com\qatraining\cad\vehicle
CLASSPATH=.;\classes;\usr\des
CLASSPATH=.;\classes;\usr\des
Hvis Package er:
og:
Skal klasserne
Placeres I en af
følgende :
There is a simple mapping from package name to directory name, which is only parameterised by
the variable CLASSPATH. If the compiled classes are not placed in the correct directory or do not
have the correct name, they will be inaccessible to the Java interpreter.
Noter til
Side 67 af 124
The CLASSPATH variable contains a list of root directories where the JVM will look for class
files. Class files should be placed in a subdirectory of one of these roots, within a subdirectory
structure that matches the classes’ package name.
The separators in CLASSPATH, and the directory separators are platform dependant. Thus Unix
uses a colon, ':’, for the CLASSPATH separators, and forward slash, '/' for directory separators. Dos
and Windows use a semicolon, ';’, and a backslash, '\'.
In Java source code a package is specified using a dot, '.’, as the separator.
At compile time, when a class that is being compiled references another class, the .class file of the
other class will be accessed. However, if the class file does not exist, but a .java source file is
present, the compiler will automatically compile the source code for the other class.
Specificering af en klasses package
Poul Henriksen
6
JAVA programmering
Specificering af en klasses package
Hver klasse tilhører til netop en package
default til en unavngiven “global” package
En package kan specificeres I den første sætning I en .java fil
package com.qatraining.cad.vehicle;
class Car
{
public Car () {eng = new Engine();}
public void start () {eng.start();}
public void stop () {eng.stop();}
private Engine eng;
}
package com.qatraining.cad.vehicle;
class Car
{
public Car () {eng = new Engine();}
public void start () {eng.start();}
public void stop () {eng.stop();}
private Engine eng;
}
Each class may belong to only one package. Only one package statement is allowed per file, and
this must be the first statement of the source file.
If the package statement is omitted, the class will be part of a special 'unnamed' package. An
unnamed package is ok for testing, but should never be used for released software.
All classes in a package can 'see' and use any other classes in the same package. This is not true for
classes of other packages, which must be declared public if they are to be used.
Noter til
Side 68 af 124
Access regler for package, klasser og interface
Poul Henriksen
7
JAVA programmering
Acces regler
Klasser og interfaces I en package kan være
:
Public
Højest
en public klasse pr. fil
Package (default, skrives ikke)
Medlemmer (metoder og data) I klassen kan være :
Public
Protected
Package
Private
Medlemmer I Interface er
Public (metoder)
Public static final (data)
Each class may belong to only one package. Only one package statement is allowed per file, and
this must be the first statement of the source file.
If the package statement is omitted, the class will be part of a special 'unnamed' package. An
unnamed package is ok for testing, but should never be used for released software.
All classes in a package can 'see' and use any other classes in the same package. This is not true for
classes of other packages, which must be declared public if they are to be used.
Noter til
Side 69 af 124
Kapitel 7 Garbage Collection
Garbage Collection
Når der ikke er flere referencer til et objekt
,
markeres det
for efterfølgende garbage collection
Med Garbage collection menes frigivelse af ikke anvendt
hukommelse
Garbage collection foregår automatisk
Garbage collection foregår når
:
Mængden af hukommelse der er tilrådighed for Java VM er under
en given grænse
Java VM har intet andet at lave (garbage collection har lav
prioritet)
Et objekt kan kalde System.gc() og når Java VM er istand til
det
Finalize() metoden
finalize() metoden
Garbage collection tager sig kun af frigivelse af
hukommelse
Hvis et objekt har
reference til en anden resurse
, f.eks. en fil, bør
objektet frigive denne resurse
Dette kan gøres med finalize() metoden
En finalize()
metode kaldes automatisk når et objekt
garbage collectes, men
Der er ingen garanti for hvorr
Ikke sikkert det kaldes før program exits
In other languages such as C++, a class can provide a destructor. A destructor is similar to a
constructor, except that it is called automatically just before an object is destroyed. A destructor is
normally used to free up resources held by the object, including the memory allocated to the object,
any other memory allocated by the object, open files, etc. Java manages memory automatically, so
an object does not need to explicitly free up memory. Consequently, Java does not support
destructors. Instead, to allow an object to clean up resources other than memory, such as open files,
Java allows a class to provide a finalize() method.
The finalize() method will be called automatically when the object's memory is garbage
collected. Unfortunately, as we have already seen, there is no guarantee as to when this will happen
Noter til
Side 70 af 124
or that it will happen before the program exits. Clearly, this is unacceptable if resources are scarce.
The only solution is to manage such resources manually. In other words, you define a public
dispose() method in your class, which users of your class should call when they have finished
using an object of your class.
You may still decide to use a finalize() method as last-ditch effort to clean up resources. One
thing to remember is that, if a number of classes in an inheritance hierarchy provide finalize()
methods, Java does not automatically call each one in turn (i.e. the finalize() method in the
most derived class overrides those higher up). Therefore, in your finalize() method, it is
important to call the finalize() method of your immediate superclass as the last statement of
your method. For more information on finalize(), please consult the JDK documentation.
Noter til
Side 71 af 124
Kapitel 8 Applets
Applicationer <> Applets
Poul Henriksen
1
JAVA programmering
Applicationer
<> Applets
En Java
applikation eksekveres fra kommandolinien
Operativsystemet skal stille en Java VM tilrådighed
Eller starte Java VM ved kommando promten
Startpunkt er main() metoden (
kaldes “class loader”)
Indeholder normalt en eller flere constructors
Kan være grafisk
En Java applet kørers af en Web browser
Browsere må stille en Java VM tilrådighed
Skal være en subklasse af Applet klassen
Startpunkt er init() metoden (kaldes af browseren)
Indeholder normalt ingen constructors
Er altid grafisk
All Java programs execute on a Java Virtual Machine (VM). In the case of a Java application, you
must explicitly invoke a standalone Java VM by typing:
java <classfile>
at the command prompt (or jview <classfile>, if you're using Microsoft Visual J++).
An applet is a Java program that is embedded into an HTML page in a similar way to an image. A
Java applet does not use a standalone Java VM; instead it uses one built into a Java-enabled browser
such as Navigator 3 or Internet Explorer 3.
There are some fundamental differences between Java applications and Java applets, as summarised
on the slide.
Hvordan afvikles en Applet
Poul Henriksen 2
JAVA programmering
Hvordan afvikles en Applet?
Applets er indlejret I en Web side
Web siden indeholder navnet på appletens .class fil
Applets kan loades lokalt fra en disk eller fra en Web server
Browser gør det automatisk
Som at loade et billede (GIF/JPEG/PNG)
Web server
serving page
containing
Java applet
Client machine
running
Web browser
Internet
Noter til
Side 72 af 124
When the browser interprets an HTML page that contains an embedded applet, it automatically
downloads the applet class file from the Web server.
During its execution, a Java applet may require other classes in order to perform its task. These
classes are loaded automatically as required by a class loader, which is part of the Java VM. These
classes may reside either on the local disk or on the Web server.
Note that during development, an applet can be tested with a tool called the appletviewer, which is
shipped with the JDK. This can be invoked from the command line as follows:
appletviewer <htmlfile>
Pending the release of browsers with full support for Java 1.1 (June '97), this is useful for testing
applets that use the new delegation event model.
Applet klassen
Poul Henriksen 3
JAVA programmering
Applet klassen
Arver mange metoder, nogle kaldes af AWT, f.eks.
paint(), update(), repaint()
Definerer yderligere metoder, nogle kaldes af browseren
init() bruges til initialisering
start(), stop()
destroy()
For at lave en Applet, skal der laves en subklasse af
Applet klassen og override visse metoder
Component
Component
Container
Container
Panel
Panel
Applet
Applet
As shown on the slide, the Applet class is derived from the Panel class, which is itself derived
from the Container class. The abstract Container class inherits many methods from the
abstract Component class, such as paint(), update(), repaint(), setFont(),
setBackground().
Note that update() is called automatically by the AWT whenever part of a component becomes
invalid and needs to be repainted. The default implementation of update() in the Component
class simply erases the background of the component before calling paint(). In most cases, this
behaviour is satisfactory and therefore a simple applet only needs to override paint().
You can request that the browser refresh a screen component by calling repaint()on that
component.
The Applet class provides additional methods, such as init(), start(), stop() and
destroy(), which are called automatically by the browser (or applet viewer) as described on the
next slide.
To build an applet, you must subclass the Applet class and override one or more of its methods of
its superclasses to provide the required functionality.
Noter til
Side 73 af 124
En Applets livscyklus
Poul Henriksen 4
JAVA programmering
En Applets livscklus
En applet kan være I en af fire tilstande
New Applet
New Applet
Loaded
Loaded
Running
Running
Dead
Dead
Applet()
init()
start()stop()
destroy()
paint()
The Applet class contains a number of no-argument "do-nothing" methods. When an applet is
first created, it is uninitialised; in particular, its link with the browser, known as its "applet context"
is incomplete. When an applet is fully initialised, the browser (or other applet viewer)
automatically calls its init() method, so this is when an applet should retrieve parameters from
the HTML file or add user-interface components to its container. Consequently, it is rare to include
a constructor in an applet; instead an applet overrides the init() method.
Immediately after calling an applet's init() method, the browser calls its start() method. The
start() method is also called whenever a user returns to an HTML page that contains the applet
after having gone off to other pages. So, unlike the init() method, which is only called once (at
least, with most browsers), start() maybe called repeatedly. Therefore, an applet only needs to
override the start() method if it needs to resume some activity (e.g. an animation) that was
previously stopped in the stop() method (see below).
The stop() method is called automatically whenever the user moves away from the HTML page
that contains the applet. So, like the start() method, it can be called repeatedly. The stop()
method gives an applet a chance to suspend or stop some processor-intensive activity (e.g. an
animation) that will not be visible to the user until he/she returns to the page that contains the
applet. Typically, if an applet needs to make use of background threads, these threads should be
started in the start() method and stopped in the stop() method. We'll discuss this topic in
more detail in the Multithreading chapter.
Finally, the browser calls an applet's destroy() method immediately before the applet is
unloaded from memory (and after calling is stop() method). Unlike, the finalize() method
discussed earlier, Java guarantees to call destroy() before the browser terminates, so an applet
can override this method if it needs to clean up resources other than memory (e.g. close files, etc).
However, most applets do not need to override the destroy() method.
Noter til
Side 74 af 124
Skriv en simpel Applet
Poul Henriksen 5
JAVA programmering
Skriv en simpel Applet
Lav en subklasse af Applet klassen
Det er nødvendigt, at importere klasser fra java.applet og java.awt.*
Override dens paint() metode
Overfør et objekt af typen Graphics
Tilbyder metoder til tegning af tekst, linier, former, m.m.
Programmer anvender komponenternes repaint metode for at tegne
Repaint skal ikke kaldes på standard komponenter
Brug drawString() til at skrive tekst
Må angive x og y koordinater
import java.applet.*;
import java.awt.*;
public class SayHello extends Applet {
public void paint (Graphics g) {
g.
drawString("Hello", 5, 50);
}
}
import java.applet.*;
import java.awt.*;
public class SayHello extends Applet {
public void paint (Graphics g) {
g.drawString("Hello", 5, 50);
}
}
As mentioned previously, to build an applet, you need to subclass the Applet class and override
one or more methods. You also need to import classes from two packages: java.applet and
java.awt.
In a simple applet, you need only override the paint() method. This method has a single
argument, which is a reference to a Graphics object. The Graphics class provides support for
drawing. Displaying text is a special kind of drawing, so the Graphics class provides a specific
method drawString() that has the following signature:
public void drawString(String str, int x, int y)
We'll discuss this method in more detail later in the chapter.
Afvikling af en Applet
Poul Henriksen 6
JAVA programmering
Afvikling af
en Applet
En HTML fil skal forekomme
Brug <APPLET> tagen til
at specificere appleten
Skal indeholde
CODE, WIDTH
og HEIGHT attributter
Andre attributer (CODEBASE, ALIGN, NAME, m.m.) er valgfrie
<HTML>
<HEAD>
<TITLE>Hello</TITLE>
</HEAD>
<BODY>
<APPLET CODE="SayHello.class"
WIDTH=300 HEIGHT=150>
</APPLET>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>Hello</TITLE>
</HEAD>
<BODY>
<APPLET CODE="SayHello.class"
WIDTH=300 HEIGHT=150>
</APPLET>
</BODY>
</HTML>
Noter til
Side 75 af 124
In the same way that you can use the <IMG> tag to embed an image in an HTML page, you can use
the <APPLET> tag to embed a Java applet. Within the <APPLET> tag itself, you must provide the
following information:
CODE Name of the Java class to execute ( including the .class extension)
relative to the CODEBASE (if specified) or relative to the URL of
the current HTML page.
WIDTH Initial width of the applet (in pixels)
HEIGHT Initial height of the applet (in pixels)
Note that some containers (browsers), such as Netscape Navigator, do not allow the applet to resize
itself from its initial size.
You can also define:
ALIGN Vertical alignment of applet in relation to surrounding text
CODEBASE Location of Java class file
or scripting of the applet from JavaScript
Java 1.1 also supports the ARCHIVE attribute, which specifies a list of comma-separated Java
Archive (JAR) files to be pre-loaded by the Web browser. Each JAR file can contain Java class
files, images, sounds, properties or any other resource required by the applet. In addition, each JAR
file can be digitally signed.
Don't forget to terminate the section of HTML relating to the applet using the </APPLET> tag.
Overfør parameter til en Applet
Poul Henriksen 7
JAVA programmering
Overfør parameter til en Applet
Inkluder <PARAM> tag i HTML filen
Kald getParameter() i init() metoden
Returnerer en String. Kan kræve konvertering
String s = getParameter("size");
if (s == null)
pointSize = 12;
else
pointSize = Integer.parseInt(s);
String s = getParameter("size");
if (s == null)
pointSize = 12;
else
pointSize = Integer.parseInt(s);
<APPLET CODE="Marquee.class"
WIDTH=300 HEIGHT=150>
<PARAM NAME="font" VALUE="Helvetica">
<PARAM NAME="style" VALUE="PLAIN">
<PARAM NAME="size" VALUE="24">
</APPLET>
<APPLET CODE="Marquee.class"
WIDTH=300 HEIGHT=150>
<PARAM NAME="font" VALUE="Helvetica">
<PARAM NAME="style" VALUE="PLAIN">
<PARAM NAME="size" VALUE="24">
</APPLET>
In the same way that you can pass command-line arguments to a Java application, you can pass
HTML parameters to a Java applet. To do this, you need to use the <PARAM> tag.
The <PARAM> tag requires NAME and VALUE attributes to specify the parameter's name and its
corresponding string value. Any number of <PARAM> tags can be included between the
<APPLET> and </APPLET> tags. Note that while HTML is not case sensitive, both the NAME
and VALUE strings in a <PARAM> tag are case-sensitive.
Noter til
Side 76 af 124
The applet can retrieve the value of a parameter by calling the getParameter() method of the
Applet class. This method takes a single String argument, which is the name of the attribute in
the <PARAM> tag. Note that this string is also case sensitive.
The getParameter() method always returns a String value, which is either the value of the
specified parameter or an empty string (""). You may need to convert this to a numeric type if this
is what the applet expects. For example, if the applet expects an int, you would have to use the
parseInt() class method of the Integer wrapper class (as shown on the slide).
Graphics klassen
Poul Henriksen 8
JAVA programmering
Graphics klassen
Tilbyder metoder til tegninge af tekst, linier, former m.m.
Gemmer informationer om
Size, Colour, Font,m.m.
Har et pixel-baseret koordinatsystem
(0, 0) er øverst venstre hjørne
KAld getSize() (el. size() i Java 1.0) til at få oplysning om applet-
vinduets størrelse
Returnerer et Dimension object
(0,0)
x
y
The paint() method has a single argument, which is is a reference to a Graphics object. A Graphics
object is basically a handle to the applet's "window" or display surface (the size of which is initially
specified in the HTML file). It stores graphical information about the applet's window such as its
size, position, current colour and current font. The Graphics class also provides a raft of drawing
methods as well as methods for changing the current colour and font.
Note that the AWT uses a pixel-based coordinate system in which the origin is at the top-left of the
applet's window. An applet can get the size of its window by calling its size() method (deprecated
in Java 1.1 and replaced by getSize()), which returns a reference to a Dimension object.
Noter til
Side 77 af 124
Tegne tekst
Poul Henriksen 9
JAVA programmering
Tegne tekst
Kald drawString(String s, int x, int y)
Bruger den aktuelle font og
colour
Kræver x og y koordinater til nederst venstre hjørneaf teksten
public void paint (Graphics g) {
g.drawString("Hello again!", 5, 50);
}
public void paint (Graphics g) {
g.drawString("Hello again!", 5, 50);
}
(0,0)
x
y
Hello again
baseline
You can draw text using the drawString() of the Graphics class. Note that the x and y
arguments specify the position of the left-hand end of the text's baseline. This is different from the
shape-drawing methods of the Graphics class, where x and y specify the top-left corner of the
shape's bounding rectangle.
In this simple example, we do not know the maximum height of a character in the string "Hello
again" in the current (default) font, so we have chosen a "safe" value of 50 (pixels) for the y co-
ordinate. Later in this chapter, we will learn about the getFontMetrics() method of the
Graphics class, which will allow us to discover the maximum height of any character in a given
font.
Ændring af Fonten
Poul Henriksen 10
JAVA programmering
Ændring af Fonten
Kald setFont(Font font) for at ændre
den aktuelle
font
Gælder al tekst der tegnes efterfølgende
Der skal skabes et nyt
Font objekt
De understøttede fonte inkluderer TimesRoman, Helvetica and Courier
(Serif, SansSerif og Monospaced i Java 1.1)
Understøttede styles: plain, bold eller italic
public void paint (Graphics g) {
Font f = new Font("Courier", Font.BOLD, 24);
g.setFont(f);
g.drawString("Hello again!", 5, 50);
}
public void paint (Graphics g) {
Font f = new Font("Courier", Font.BOLD, 24);
g.setFont
(f);
g.drawString
("Hello again!", 5, 50);
}
Noter til
Side 78 af 124
Text is always drawn in the current font. You can change the current font by calling the
setFont() method of the Graphics class. The details of a font are encapsulated in an object
of the Font class, so to specify a new font, you must first create a new Font object.
The Font constructor takes three arguments: the name of the font, the font style and the point size.
In Java 1.0, the supported font names are "TimesRoman", "Helvetica", "Courier", "Dialog" and
"DialogInput". In Java 1.1, "Serif", "SansSerif" and "Monospaced" should be used instead. The
font style should be one of the constants Font.PLAIN, Font.BOLD or Font.ITALIC (or the
combination Font.BOLD | Font.ITALIC).
Note that, in practice, it would more efficient to create a new Font object in init() rather than in
paint().
Ændring af farve
Poul Henriksen 11
JAVA programmering
Ændring af farve
Kald setColor(Color c) til at ændre farven
Anvendes på alle efterfølgende tegne operationer
Standard farver der understøttes
Eks. Color.red, Color.blue, Color.magenta,m.m.
Det er kun nødvendigt, at skabe et Color objekt for ikke-standard
farver
Kald setBackground() for at ændre baggrundsfarven
public void paint (Graphics g) {
g.setColor(Color.red);
g.drawString("Hello again!", 5, 50);
}
public void paint (Graphics g) {
g.setColor(Color.red);
g.drawString("Hello again!", 5, 50);
}
// create new colour in r, g, b format
Color myColor = new Color(0, 0, 100);
g.setColor(myColor);
. . .
// create new colour in r, g, b format
Color myColor = new Color(0, 0, 100);
g.setColor(myColor);
. . .
Text, lines and shapes are always drawn in the current colour. You can change the current colour
by calling the setColor() method of the Graphics class. As you might expect, a colour is
represented by an object of the Color class (note the US spelling). However, if you want to
change the current colour, you do not necessarily need to create a new Color object, because the
Color class defines thirteen standard colours. These are shown in the following table:
black darkGray lightGray pink yellow
blue gray magenta red
cyan green orange white
These standard colours are represented by constants, e.g. Color.black, Color.blue, etc.
If you want a non-standard colour, you must create a new Color object and specify its red, green
and blue components (either as integral values between 0 and 255, or as floating-point values
between 0.0 and 1.0).
To set the background colour of the applet's window, you must call the setBackground()
method of the Component class.
Noter til
Side 79 af 124
Tegning af linier og former
Poul Henriksen 12
JAVA programmering
Tegning af linier og former
Linie
drawLine()
Pil
drawArc
() og fillArc()
Rektangler
drawRect() og fillRect()
draw3DRect() og fill3DRect()
Afrundede rektangler og ovaler
drawRoundRect
() og fillRoundRect()
drawOval() og fillOval()
Polygoner
drawPolygon() og fillPolygon()
Alle anvender den aktuelle farve der er sat I graphic
objektet
Linier og rammer har en bredde på en pixel
The Graphics class provides methods for drawing lines, arcs and various shapes. It also provide
methods for drawing shapes that are filled with the current colour. For example, the following
method:
void drawLine(int x1, int y1, int x2, int y2)
draws a line between the points (x1, y1) and (x2, y2). Similarly, the following method:
void fillRect(int x, int y, int width, int height)
draws a filled rectangle, where (x,y) is the position of top-left hand corner.
Note that all lines are one pixel wide, except for the shadowed sides of 3D rectangles, which are all
of three pixels wide.
The following code fragment shows how you might use the fillRect() method to display the
contents of an array of numeric values as a bar chart.
// Get size of applet's window
Dimension d = getSize(); // replaces 1.0 size() method
int clientWidth = d.width;
int clientHeight = d.height;
// Calculate width of each bar
int barWidth = clientWidth/values.length;
// Calculate scaling factor
double scale = clientHeight/maxValue;
// Draw the bars
g.setColor(Color.red);
for (int i = 0; i < values.length; i++) {
int x1 = i * barWidth + 1;
int y1 = (int)((maxValue - value[i]) * scale);
int barHeight = (int)(values[i] * scale);
g.fillRect(x1, y1, barWidth-2, barHeight);
}
Noter til
Side 80 af 124
Sikkerhed ved Applets
Poul Henriksen 13
JAVA programmering
Sikkerhed ved Applets
Browser sætter begrænsninger for hvad en applet
kan gøre
Applets
Kan ikke tilgå det lokale file system
Har ikke adgang til adre systemer eller netværkstilgang bortset fra web
serveren
Kan starte nye programmer
Kan ikke afslutte Java runtime systemet
Kan ikke ændre sikkerhedsrestriktionerne
Vinduer der er skabt af applets er markeret som
untrusted
One of the main concerns about Java applets is that the browser downloads code across the
network, possibly from an unknown or untrusted source, and executes it on the client's system. This
is a classic seeding ground for viruses, which could potentially damage the client's system
intentionally or unintentionally.
To alleviate these fears, certain security restrictions are placed on applets. To start with, Java
applets are inherently more secure than many other types of component. For example, Java does
not support pointers, so is impossible to access invalid memory locations either intentionally or
unintentionally. In addition, the class loader in the Java VM checks the bytecodes in the Java class
file to make sure that they haven't been tampered with since compilation.
Java-enabled browsers also place certain security restrictions on applets, so that applets are only
allowed to play in a "sandbox". For example, Netscape Navigator 3 and Internet Explorer 3 do not
allow applets to access files on the local disk or to communicate with systems on the network apart
from the Web server that provided the HTML page that contained the applet. The latter is
important if the client's system is behind a firewall. Also, any dialog window created by an applet
is noted as untrusted in its status line.
In Java 1.1, an applet provider can sign a Java applet with a digital signature to verify that it comes
from a trusted source. If such an applet is downloaded by a Java 1.1-enabled browser, the client has
to decide whether he/she trusts the applet provider. If so, the browser may grant extended powers
to the applet.
Noter til
Side 81 af 124
Eksempler
Poul Henriksen 14
JAVA programmering
Eksempler
Lommeregner
Eksempel Applet_Spot
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/**
AppletComp implementerer ActionListener, hvilket betyder, at vi skal
override metoden public void actionPerformed(ActionEvent event)
*/
public class Applet_Spot extends Applet implements ActionListener,MouseListener,ItemListener{
Button button_op, button_ned;
Spot s ;
public static int x;
public static int y;
public static Choice choice;
Button button_v, button_h;
public static Color color;
Color[] colors = {Color.blue,Color.red,Color.green};
public void init () {
/*
Opretter en Button instans og tilføjer den til anApplet.
Herefter kaldes Button_op.addActionListener(this),
hvilket betyder, at den aktuelle applet (this)
kan behandle events forårsaget af klik på disse buttons.
*/ x = 50;
Noter til
Side 82 af 124
y = 50;
choice = new Choice();
choice.addItem("Blå");
choice.addItem("Rød");
choice.addItem("Grøn");
this.add(choice);
button_op = new Button("OP");
this.add(button_op);
button_op.addActionListener(this);
button_ned = new Button("NED");
this.add(button_ned);
button_ned.addActionListener(this);
button_v = new Button("VENSTRE");
this.add(button_v);
button_v.addActionListener(this);
button_h = new Button("HØJRE");
this.add(button_h);
button_h.addActionListener(this);
s = new Spot(new Point(50,50), Color.blue);
this.addMouseListener(this);
choice.addItemListener(this);
} // end init
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
s = new Spot(new Point(x,y),color);
Noter til
Side 83 af 124
repaint();
}
public void itemStateChanged(ItemEvent e){
color = colors[choice.getSelectedIndex()];
s = new Spot(new Point(x,y),color);
repaint();
}
public void paint(Graphics g){
s.draw(g);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == button_op)
s.op();
if (event.getSource() == button_ned)
s.ned();
if (event.getSource() == button_v)
s.venstre();
if (event.getSource() == button_h)
s.hoejre();
repaint();
}
} //end Applet_Spot
class Spot{
int r = 20;
Color c;
Point p;
Spot(Point p, Color c){
this.p = p;
this.c = c;
}
void draw(Graphics g) {
g.setColor(this.c);
g.fillOval(p.x - r, p.y - r, r * 2, r * 2);
}
void ned(){
p.y += 5;
}
void op(){
Noter til
Side 84 af 124
p.y -= 5;
}
void venstre(){
p.x -= 5;
}
void hoejre(){
p.x += 5;
}
} // end Spot
Noter til
Side 85 af 124
Kapitel 9 Komponenter i JAVA-UI
Overblik over komponenter i JAVA-UI
Poul Henriksen 1
JAVA programmering
Overblik
over komponenter
I JAVA UI
AWT (java Abstract Window Toolkit) består :
standard komponenter:
subklasse af AWT component
klassen
eks. Button, List, Menu, Textarea
Canvas r det muligt at skabe dine egne komponenter
cointainere :
Subklasse af cointainer klassen
eks. Windows, Menubars, Dialog, panel
Kan indeholde andre componenter
Layout managers
Hver enkelt container har en layoutmanager
Komponenterne fylder ikke det samme på
alle systemer. Fixed
position ikke smart
Layputmanagers tilpasser til de aktuelle forhold
Drawing
Graphics klassen bruges til at tegne
danner en kontekst hvori der tegnes.
Events
AWT definerer en r
ække forskellige event listener
Det afhænger af komponenten hvilke events der kan registreres.
En Komponent generer kun de events for hvilke der er registreret listeners
The model-view paradigm is common in object-oriented programming. The approach divides a
program into data-models and views on those models. The views must be informed of changes in
the model.
An inefficient approach to implementing this model is to use a polling loop -i.e. the views could
repeatedly check the model to establish if a change has taken place. A better approach is to have the
model contact the views when a change occurs.
The model must know which views it should contact in response to the occurrence of particular
events. This is achieved by allowing views to register with a model. Each view registers an
interest in the state of certain models, and is notified by those models when a state change takes
place.
An implementation of the registration and notification process must address certain issues - how
should the model contact the views and inform them of the change which has taken place. A
communication protocol is required. Java uses interfaces to solve this problem and provide a
protocol for communication. Views are only permitted to register with the model if they implement
a specified interface. The interface defines methods which the model can invoke on the registered
views to notify them of state changes.
Noter til
Side 86 af 124
AWT komponenter
Poul Henriksen
2
JAVA programmering
AWT
komponenter
AWT component(er)
er grafiske
brugergrænseflade komponenter
Arver fra java.awt.Component
Er kilde til AWT Events
Tilbyder event-håndteringsmetoder
En kompopnent skal tilføjes til en
Container for at blive vist
Container tilbyder en add() metode
Button
Button
Checkbox
Checkbox
Choice
Choice
Label
Label
List
List
Scrollbar
Scrollbar
Component
Component
TextComponent
TextComponent
TextArea
TextArea
TextField
TextField
All components (except for menus) are implemented as subclasses of the Component class. From
the Component class, they inherit the following:
The paint(), update(), and repaint() methods that provide the infrastructure for
components to draw themselves.
Methods for getting/setting the keyboard focus, enabling/disabling mouse and keyboard control of
components.
Methods for getting/setting the current font, getting information about the current font,
getting/setting the foreground colour and getting/setting the background colour.
Methods to get and set the component size/position and allow components to report their preferred
and minimum sizes. Component sizes and positions are normally determined by layout managers.
Methods to show/hide the component and check if it is visible.
An implementation of ImageObserver interface and methods to help display images. Note that
most components cannot display images, since their appearance is implemented in platform-specific
code.
Components can also be the source of AWT Events, and so provide addXXXListener() and
removeXXXListener() methods for the registering and de-registering of event listeners.
We can add a Component to any object which inherits from java.awt.Container (this
includes all Applets). The Container class provides a method add() which takes a
Component as its parameter.
Noter til
Side 87 af 124
Label og Button
Poul Henriksen
3
JAVA programmering
Label
og Button
Label klassen
Viser en enkelt linie af read-only tekst
Tekst alignment kan specificeres til constructor eller ved at kalde
setAlignment()
Tekst kan specificeres til constructor eller ved kald af setText()
Genererer ingen events
Button
klassen
En standard implementering af en knap
En
trykknap der viser en tekst label
Label kan specificeres til constructor eller ved kald af setLabel()
Når brugeren trykker på en knap,
genereres
et ActionEvent
The Label class provides uneditable, unselectable text. Labels can be left-aligned, centered or
right-aligned by specifying Label.LEFT, Label.CENTER or Label.RIGHT either to the
Label constructor or to its setAlignment() method. As with any component, you can specify
its background colour, foreground colour and font, although this may not work with the Windows
95/NT implementation of the Java 1.0 AWT.
The Button class represents a simple pushbutton which responds to being clicked. As with most
components, the appearance of buttons depends on the platform they are running on and you cannot
change the look using a Button subclass. The only facets of a button's appearance that you can
change without creating your own class are the font and text it displays, and its foreground and
background colours. The Button class has getLabel() and setLabel() methods, which allow
you to query and set a button's textual label.
ActionEvents are generated when the button is clicked with the mouse.
Noter til
Side 88 af 124
Tekst input
Poul Henriksen
4
JAVA programmering
Tekst Input
TextField Klassen
Viser et enkeltlinie tekstfelt, der kan være editerbart
Tekst kan specificeres til en constructor
TextArea klassen
Viser flerlinie tekst, der optionelt kan editeres
Tekst kan specificeres til constructor eller ved
at kalde
append(),
insert() eller replace()
Constructor muliggør, at man sætter antal rækker og kolonner
Begge arver fra TextComponent klassen
Teksten kan gøres editerbart ved at kalde setEditable()
Tekst kan ændres ved at kalde setText
()
Man kan forespørge på teksten ved at kalde getText()
The TextArea and TextField classes display selectable text and, optionally, allow the user to
edit the text. They both inherit from the TextComponent class, which provides for
setting/getting the current selection, enabling/disabling editing and getting/setting the currently
selected text. You cannot change the basic appearance of either component because this is defined
by the platform-specific peer component.
As for any component, you can specify a text component's background colour, foreground colour
and font, although this may not work with the Windows 95/NT implementation of the Java 1.0
AWT.
Komponenter til bruger valg
Poul Henriksen
5
JAVA programmering
Komponenter til bruger valg
Checkbox klassen
Viser en checkbox sammen med en tekst label
Består af knapper der enten kan være on eller of
Kan ændre fremtræden/opførsel til radio-button ved at tilknytte et
CheckboxGroup object
Når brugeren klikker på en checkbox, genereres et ItemEvent
getStateChange() returnerer ændringens type :
SELECTED /
DESELECTED
Choice klassen
En drop-down menu
Tilføjer et tekst emne ved at kalde addItem()
Forespørgsel på brugervalg ved kald af getSelectedItem()
Når brugeren klikker på en checkbox, genereres et ItemEvent
Dens getItem() metode returnerer det element der er påvirket af en
event
Noter til
Side 89 af 124
The Checkbox class provides a two-state button that can be either on or off. Clicking on a
checkbox toggles its state. The Checkbox class has getState() and setState() methods for
setting or querying the state of a checkbox.
If you want a group of checkboxes in which only one checkbox at a time can be "on" (commonly
called a radio button group), you can create a CheckboxGroup object to oversee the checkboxes.
Pushing any button in a checkbox group turns it on and turns the other buttons off.
The Choice class provides a single-line text item and an associated button. Pressing the button
reveals a drop-down list of choices. When the user selects one of the items, the drop-down list
disappears and the selected item then appears as the single-line text.
The Choice class has methods to allow items to be added, selected or deselected. There are also
methods to count the number of items and to obtain the selected item.
Event Model
The Java 1.1 Delegation Event Model is based on the concept of an event source and an event
listener. (Think of the source as being the model and the listener as being a view on the source.)
An event source is any object (e.g. an AWT component such as a Button) which can generate
events. An event listener is an object that is interested in being notified when an event occurs. When
a source generates an event, it notifies its listeners by passing them an event-object.
Sources can generate different types of events. Each type of event is represented by a subclass of
java.util.Event. For example, AWT ActionEvents are represented by the
java.awt.event.ActionEvent class.
Sources provide methods to allow listeners to register an interest in events. The registration
methods are event-specific, that is, there is a registration method for listeners interested in
ActionEvents, and a separate registration method for listeners interested in KeyEvents etc.
Each type of event if paired with a listener interface, so for example, ActionEvent is paired
with the interface ActionListener; while KeyEvent is paired with the interface
KeyListener etc. The listener interfaces provide the basis for a protocol for registration and
notification.
Noter til
Side 90 af 124
Events
Poul Henriksen
7
JAVA programmering
Events
java.util.EventObject er superklassen
for alle
events
java.util.EventObject
java.util.EventObject
java.awt.AWTEvent
java.awt.AWTEvent
java.awt.event.ActionEvent
java.awt.event.ActionEvent
java.awt.event.AdjustmentEvent
java.awt.event.AdjustmentEvent
java.awt.event.ItemEvent
java.awt.event.ItemEvent
java.awt.event.TextEvent
java.awt.event.TextEvent
Subklasser af
AWTEvent
der
findes I package
java.awt.event
java.util.EventObject is the superclass for all event objects used by the Java 1.1 AWT.
This class provides a single constructor and a couple of public methods as follows:
public class EventObject extends Object implements
Serializable
{
public EventObject(Object source);
protected transient Object source;
public Object getSource();
public String toString();
}
Note that every event object has an instance variable called source which is used to store a reference
to the object which generated the event. The source variable is initialised through the event’s
constructor, and can be obtained by calling getSource().
The EventObject class is extended by more specific classes in the java.awt.event
package. Each type of AWT event is represented by a subclass of java.awt.AWTEvent.
Noter til
Side 91 af 124
AWT Events og deres kilde
Poul Henriksen
8
JAVA programmering
AWT Events
og deres kilde
AWT Events genereres I AWT
komponenter
AWT komponenter er kilde til AWT Events
Komponenter sender events til alle registrerede
listeners
Event
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent
Cause / Source
User clicked on button, selected menu item, pressed
<Return> in text component or double-clicked item in list
User moved scrollbar
User selected or deselected checkbox, radio button, list
item or choice item
User changed text in text component
AWT Components (Button, MenuItem, TextArea, etc) are the source for AWT Events.
When an event is generated on a component, it sends the event to all registered event listeners.
Different components generate different events in response to different user actions:
An action event, as represented by the ActionEvent class, is a "high-level" event that is
generated when a user interacts in some way with an AWT component and expects some action to
occur. For example, an action event is generated if a user clicks on a Button component, or
selects a MenuItem object in a menu. Action events are also generated if a user hits the <Return>
key in a TextField or TextArea component, or double clicks an item in a List component.
A useful method of the ActionEvent class is getActionCommand(), which returns the name
of the component or, if it doesn't have a name, its label.
Action events are not generated if a user selects or deselects a Checkbox component, or single-
clicks an item in a Choice or List component. Instead, an ItemEvent is generated. The
getStateChanged()method returns the new state of the item: ItemEvent.SELECTED or
ItemState.DESELECTED.
An adjustment event, as represented by the AdjustmentEvent class, indicates that the user has
adjusted the value of an Adjustable object, such as a ScrollBar component. The
getValue() method returns the new value of the Adjustable object. Several types of
adjustments can be made to an Adjustable object and getAdjustmentType() returns one
of five constants to indicate which type has occurred.
A text event, as represented by the TextEvent class, indicates that the user has changed the
displayed text in a TextField or TextArea component.
In addition, there are several types of lower level events which are ComponentEvent and
subclasses of it, including FocusEvent, KeyEvent, MouseEvent, PaintEvent,
WindowEvent.
Noter til
Side 92 af 124
AWT Event-Listener Interfaces
Poul Henriksen
9
JAVA programmering
AWT Event
-Listener Interfaces
Til hver AWT Event er der et listener interface
Placeret i java.awt.event
Listeners der ønsker at blive notificeret af AWT Events
skal implementere det korresponderende listener interface
Metoderne tager en event
som parameter
Interface
Method(s)
ActionListener
AdjustmentListener
ItemListener
TextListener
actionPerformed(ActionEvent)
adjustmentValueChanged(AdjustmentEvent)
itemStateChanged(ItemEvent)
textValueChanged(TextEvent)
For every AWT event type there is a corresponding event-listener interface. Listeners which need to
be notified of AWT Events must implement the associated interface.
The interface methods take a single argument of the event-type associated with the Listener
Interface. Event sources can therefore use these methods to pass an event-object to event listeners
which implement the interface.
Once an event listener has received an event object, it can discover the source of the event by
calling one of the event object’s accessor methods, such as getSource().
Registrering af en Event-Listener
Poul Henriksen 10
JAVA programmering
Registering af en Event-Listener
Kilder sender kun events til registerede listeners
Tilføjelse og fjernelse af listener vha. Metoder af formen
:
addXXXListener() og removeXXXListener()
Argument af interface typen XXXListener
// create ActionListener and ActionEvent source
MyListener listener = new MyListener();
Button button = new Button(“press here”);
// register the listener’s interest in the Button’s ActionEvents
button.addActionListener(listener);
// create ActionListener and ActionEvent source
MyListener listener = new MyListener();
Button button = new Button(“press here”);
// register the listener’s interest in the Button’s ActionEvents
button.addActionListener(listener);
// implement an event listener for ActionEvents
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
System.out.println(“An Action Event Occurred”);
}
}
// implement an event listener for ActionEvents
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
System.out.println(“An Action Event Occurred”);
}
}
When an event occurs, the source notifies its listeners of the occurrence. But for this to happen, the
listeners must first register their interest in that kind of event happening in that particular source.
Registration:
Noter til
Side 93 af 124
Sources provide methods to allow listeners to register or de-register their interest in particular types
of event. A different registration method is provided for each type of event that the source can
generate. The registration methods each take a parameter of a suitable listener interface type:
Sources of ActionEvents provide a registration method addActionListener() which takes an
argument of the interface type ActionListener. Sources of MouseEvents provide an
addMouseListener() method which takes an argument of the interface type MouseListener, and so
on.
The effect of this system is that an object can only register as a listener for a particular type of event
if it implements the corresponding interface. The compiler will check to ensure that this is so.
The benefit of using this system is that the source can rely on the fact that all listeners which have
registered an interest in a certain event type are guaranteed to implement the method(s) declared in
the associated listener interface. Thus the source can safely call the interface method(s) on the
registered listeners. For example, a Button which only allows ActionListeners to register an interest
in its ActionEvents can safely call actionPerformed() on all those registered listeners because
actionPerformed() is declared in the ActionListener interface.
This a very flexible system - any object can register an interest in a component’s events so long as
that object implements the right interface.
Sources also provide methods for de-registering listeners e.g. removeActionListener(),
removeMouseListener(), removeKeyListener() etc.
Event Notificering
Noter til
Side 94 af 124
Et simpelt eksempel
Poul Henriksen
12
JAVA programmering
Et
simpelt eksempel
En applet som listens
OK og
Cancel
knapper
import java.awt.*;
import java.awt.event.*;
public class MyApplet extends Applet implements
ActionListener {
Button okButton, cancelButton;
public void init() {
add(okButton = new Button("OK")); // add Button to Applet
okButton.addActionListener(this); // register listener
add(cancelButton = new Button("Cancel"));
cancelButton.addActionListener(this);
}
public void
actionPerformed(ActionEvent ae) {
Object source = ae.getSource(); // source returned as type Object
if (source == okButton) { // is the source the okButton?
// perform action for OK button . . .
} // etc for cancelButton. . .
}
}
import java.awt.*;
import java.awt.event.*;
public class MyApplet extends Applet
implements ActionListener {
Button okButton, cancelButton;
public void init() {
add(okButton = new Button("OK")); // add Button to Applet
okButton.addActionListener(this); // register listener
add(cancelButton = new Button("Cancel"));
cancelButton.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource(); // source returned as type Object
if (source == okButton) { // is the source the okButton?
// perform action for OK button . . .
} // etc for cancelButton. . .
}
}
Here is a simple example in which an Applet acts as the event-listener for an OK and a Cancel
button. First, we need to import the Java 1.1 event classes and AWT components from the
packages: java.awt.event and java.awt. [Packages and the import statement are
discussed in the next chapter.] Also, the applet must implement the ActionListener interface.
In the init() method, we create a couple of buttons and store the reference to each button in an
instance variable. Each Button must be added to the Applet - using an add() method which the
Applet inherits from the Container class.
We then register the applet as an action listener for both buttons by specifying this in the calls to
the buttons' addActionListener() methods. By the way, it is very easy to forget to do this
and wonder why your applet doesn't respond to button clicks!
When the user clicks a button, the Button object generates an ActionEvent object, which
describes the event. Then the Button object calls the actionPerformed() method on all
registered action-listeners, which in this case is the applet alone. The actionPerformed()
method has a single argument, which is a reference to the ActionEvent object previously
created by the Button object.
In the actionPerformed() method, we identify the source of the event by calling the
getSource() method of the ActionEvent object. Note that getSource() returns a
reference of type Object. To determine which button was clicked, we simply compare the source
reference with the reference to each button.
Noter til
Side 95 af 124
Flere AWT Events
Poul Henriksen
13
JAVA programmering
Flere
AWT Events
Nogle events er fælles for mange AWT komponenter
FocusEvent, MouseEvent, KeyEvent, m.fl.
Component klassen tilbyder registreringsmetoder
addFocusListener(), addMouseListener, addKeyListener
() osv
.
Hver eventtype har et matcherende interface
FocusListener, MouseListener, KeyListener osv.
Hvert interface definerer flere metoder
Event Listener skal implementere alle metoder I interfacet
e.g. MouseListener defines:
mouseClicked()
mouseEntered()
mouseExited()
mousePressed()
mouseReleased()
Most AWT Components can receive low-level events, such as FocusEvent, MouseEvent and
KeyEvent. The class java.awt.Component provides registration and de-registration methods
for event listeners interested in these events.
As always, the Event classes are matched with Listener Interfaces - found in java.awt.event
With the high-level semantic events which we saw earlier, each listener interface defined only a
single method. With the low-level semantic events, a listener may define several methods. (N.B. a
listener class implementing the interface must provide implementations of all the interface’s
methods.)
Low-level events possess an ID which reflects the situation in which they occur, and the event-
listener interface for an event will therefore define a separate method for each event ID.
For example, the KeyListener interface has three methods: keyPressed(),
keyReleased(), and keyTyped(). When a KeyEvent is generated it is given an ID -
signifying the kind of KeyEvent that occurred - and it is then passed to registered
KeyListeners using the appropriate method call.
Mouse events are treated in a special way, because there are two event-listener interfaces that
correspond to mouse events. MouseListener has five methods: mouseClicked(),
mouseEntered(), mouseExited(), mousePressed() and mouseReleased().
MouseMotionListener has two methods: mouseDragged() and mouseMoved().
Note that KeyEvent and MouseEvent have a common superclass - InputEvent The
InputEvent class defines a method getWhen() which returns a long timestamp value
indicating when the event took place.
Noter til
Side 96 af 124
En Mouse og Item Listener
Poul Henriksen
14
JAVA programmering
En Mouse
og Item Listener
En Applet ønsker at lytte efter valg I en Choice komponent og efter
MouseClicks
Må registreres som ItemListener og MouseListener
public class SpotPainter extends Applet
implements ItemListener, MouseListener {
private Color[] colors = {Color.blue, Color.red};
private int x, y; // x,y co-ordinates for painting spot
private int index;
// index for colors array
public void init(){
Choice choice = new Choice();
choice.add(“blue”); // add items to choice
choice.add(“red”);
add(choice); // add choice to Applet
choice.addItemListener(this); // register as Item listener
this.addMouseListener(this); // register as Mouse listener
}
public void paint(Graphics g){
g.setColor(colors[index]); // set colour using index
g.fillOval(x,y,20,20); // paint spot at x,y position
}
/
/ continued . . .
public class SpotPainter extends Applet
implements ItemListener, MouseListener {
private Color[] colors = {Color.blue, Color.red};
private int x, y;
// x,y co-ordinates for painting spot
private int index; // index for colors array
public void init(){
Choice choice = new Choice();
choice.add(“blue”);
// add items to choice
choice.add(“red”);
add(choice); // add choice to Applet
choice.addItemListener(this); // register as Item listener
this.addMouseListener(this); // register as Mouse listener
}
public void paint(Graphics g){
g.setColor(colors[index]); // set colour using index
g.fillOval(x,y,20,20); // paint spot at x,y position
} /
/ continued . . .
Now that you know more about the different types of AWT components and events, let's look at a
slightly more complex example in which we implement two event-listener interfaces. This is an
applet which draws spots onto the screen in a colour which the user selects from a Choice menu.
The applet draws the spot in response to a mouse-click, using the x,y co-ordinates of the mouse-
click as the new location for the spot.
The applet displays a Choice menu holding the colour labels “red” and “blue”. The applet
implements the ItemListener interface and registers with the Choice to listen for item
selected and de-selected events. [As shown on the following slide, the applet responds to
ItemEvents by altering the index variable which is used in conjunction with the “colors” array.]
The applet also registers with itself as a MouseListener - so that it can respond to mouse-clicks.
In the paint method of the applet, the Graphics colour is set to the Color object located in the
“colors” array at the position denoted by the variable index. An oval is then painted at the screen co-
ordinates represented by the applet’s x , y variables.
The code for event-handling is continued on the next slide.
Noter til
Side 97 af 124
Behandling af Events
Poul Henriksen
15
JAVA programmering
Behandling af
Events
Når der vælges i Choice kaldes itemStateChanged()
mouseClicked()kaldes når musen klikkes
Alle MouseListener metoder skal implementeres
public void itemStateChanged(ItemEvent evt){
Choice ch = (Choice)evt.getSource();
index = ch.getSelectedIndex(); //index of selected item
}
public void itemStateChanged(ItemEvent evt){
Choice ch = (Choice)evt.getSource();
index = ch.getSelectedIndex(); //index of selected item
}
public void mouseClicked(MouseEvent e){
x = e.getX(); y = e.getY(); // get X,Y co-ordinates
repaint();
// paint the screen
}
public void mouseClicked(MouseEvent e){
x = e.getX(); y = e.getY(); // get X,Y co-ordinates
repaint(); // paint the screen
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
Fire måder at implementere Listener interface
Poul Henriksen 16
JAVA programmering
Fire måder at implementere Listener interface
Direkte implementering af interface
class A implements XxListener {
implementer alle metoder i XxListener
evt. tomme metoder
}
Omstændigt, at implementere alle metoder i interfacet, hvis kun en eller få
skal anvendes.
Arv af adapter
XxAdapter implementerer XxListener - men alle metoder har tomme kroppe.
class A extends XxAdapter {
override udvalgte metoder fra XxAdapter
}
Kan kun bruges hvis A ikke arver fra andre klasser.
In the java.awt.event package, standard adapter classes are provided for those event-listener
interfaces that have more than one method, e.g. the MouseListener interface. Each adapter
class is a trivial implementation of the corresponding interface; it simply provides "null" methods
(empty bodies) for each of the methods of that interface. So, for example, the MouseAdapter
class defines five null methods as shown on the slide. When a listener is not interested in all of the
methods of a listener interface, it is often easier and cleaner to subclass the adapter class rather than
to implement the listener interface.
Obviously, this technique cannot be used if the listener class already subclasses another class, but,
as we shall see, this limitation can easily be overcome by using an inner class.
Noter til
Side 98 af 124
Poul Henriksen 17
JAVA programmering
Fire
måder forsat
……
Inner class
Det er tilladt at lave en klasse inden i en anden klasse:
class A {
class
MinAdapter extends
XxAdapter {
// inner class
// override udvalgte metoder i XxAdapter
}
...
new
MinAdapter();
}
Anonym class
Man kan lave anonyme klasser (uden navn)
-
bruges til at lave é
t objekt af
denne klasse
obj.addXxListener(new XxAdapter() {
// Nyt objekt af klasse, der arver fra XxAdapter
// override
udvalgte metoder i
XxAdapter
}
);
Standard Adapter klasser
Poul Henriksen 18
JAVA programmering
Standard Adapter klasser
java.awt.event package tilbyder nogle standard
adapter klasser
F.eks. FocusAdapter, MouseAdapter, KeyAdapter, m.fl.
Hver tilbyder en triviel implementation af listener interfacet
Hvis man kun skal anvende en mindre del af metoderne I interfacet, er
det nemmere, at lave en subklasse af en adapterklasse.
Override kun metoder, som du skal anvende
Husk en klasse kan kun arve fra en klasse
public abstract class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
public abstract class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
In the java.awt.event package, standard adapter classes are provided for those event-listener
interfaces that have more than one method, e.g. the MouseListener interface. Each adapter
class is a trivial implementation of the corresponding interface; it simply provides "null" methods
(empty bodies) for each of the methods of that interface. So, for example, the MouseAdapter
class defines five null methods as shown on the slide. When a listener is not interested in all of the
methods of a listener interface, it is often easier and cleaner to subclass the adapter class rather than
to implement the listener interface.
Obviously, this technique cannot be used if the listener class already subclasses another class, but,
as we shall see, this limitation can easily be overcome by using an inner class.
Noter til
Side 99 af 124
Eksempel på eventhåndtering i en anonym klasse
Poul Henriksen
19
JAVA programmering
Eks: på eventhåndtering I en anonym klasse
public class MyFrame extends Frame {
public static void main(String[] args) {
final Frame f = new MyFrame();
f.addWindowListener
(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.setSize(300,250);
f.show();
. . .
public class MyFrame extends Frame {
public static void main(String[] args) {
final Frame f = new MyFrame();
f.addWindowListener(new
WindowAdapter
(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.setSize(300,250);
f.show();
. . .
If your window is to respond to WindowEvents you must register a WindowListener. A tidy
way of achieving this is to use an anonymous inner class which extends from WindowAdapter.
(WindowAdapter provides null implementations of all the methods declared in the
WindowListener interface.) In the example on the slide, the inner class can refer to the local
Frame variable f defined inside the main method because f has been declared final.
System.exit(0) exits the application.
By default, a new window is hidden and has zero size, so it is necessary to call its setSize()
and show() methods, as shown in the example on the slide.
To create a window the size of the user’s screen, set the window’s size using a Dimension object
retrieved via the Toolkit class:
Frame f = new MyFrame();
Dimension dm = Toolkit.getDefaultToolkit().getScreenSize();
f.setSize(dm.width,dm.height);
f.show();
Noter til
Side 100 af 124
Eksempler
Poul Henriksen
20
JAVA programmering
Eksempler
Mustest.java
Lommeregner.java
ButtonDemo
CheckBoxDemo
ChoiceDemo
Se udleverede eksempler.
Noter til
Side 101 af 124
Kapitel 10 AWT Container
Poul Henriksen
1
JAVA programmering
Component
Component
Container
Container
Panel
Panel
Applet
Applet
Window
Window
Dialog
Dialog
FileDialog
FileDialog
Frame
Frame
ScrollPane
ScrollPane
Java 1.1
only
AWT Container
AWT komponenter kan tilføjes til en AWT container
Eks. applet, panel, frame eller dialog
AWT container arver fra Component klassen
Herved kan en container tilføjes til en anden container
The Container class is an abstract class representing a component that can contain other
components. Concrete subclasses of the Container class include Panel, Applet, Frame and
Dialog. Once a Container object has been created, components can be added to it with
add(), and removed using remove(). getComponents() returns an array of the components
contained in a Container object.
Containers
Poul Henriksen 2
JAVA programmering
Containers
Enhver AWT komponent skal tilføjes til et container objekt for at
blive vist.
Containerobjekt.add(komponentobjekt)
En container er I sig selv en component, og kan tilføjes til en anden
container
Eksempler på container
Dialog
Er vinduer der er afhængig af andre vinduer.
Kan være modal eller non modal
Modal : forhindrer brugeren I at gøre andet indtil dialogen er afsluttet
Frames
Danner vinduer til applikationer og applets
En grafisk applikation behøver mindst en frame
Panel
Container med generelle anvendelsesmuligheder
Kan anvendes til at indlejre en container I en anden container
The visual layout of a components in a container is performed, not by the container itself, but by an
associated layout manager.
A layout manager is any class that implements the LayoutManager interface. The standard
AWT layout managers are the FlowLayout, BorderLayout, GridLayout,
Noter til
Side 102 af 124
GridBagLayout and CardLayout classes. You can also implement your own custom layout
manager derived from the LayoutManager interface.
A container specifies which layout manager to use by calling the setLayout() method. This
can specify an instance of a layout manager or null, which means that no layout manager is
required. Components are then added to the container using the add() method. Thereafter, the
precise layout of the components is determined by the layout manager associated with the
component's container.
You can position components without using a layout manager, but this is unsuitable for applets and
other platform-independent programs, since the size of components can be different on different
platforms.
Layout håndtering
Poul Henriksen 3
JAVA programmering
Layout
håndtering
Visuel
layout
af komponenter I en container styres af et tilknyttet
layout manager
object
Placerer og tilpasser komponenter udfra nogle generelle regler
Tilbyder platforms-uafhængighed
AWT tilbyder et
antal standard layout manager
klasser, eks
.
FlowLayout
BorderLayout
GridLayout
GridBagLayout
Hver
type af container
har en default layout manager
FlowLayout er default for applets og panels
BorderLayout
er default for frames og dialogs
For at specificere en anden
layout manager
Skab et nyt layout manager objekt af den
ønskede klasse
Kald Container klassen setLayout() metode
The visual layout of a components in a container is performed, not by the container itself, but by an
associated layout manager.
A layout manager is any class that implements the LayoutManager interface. The standard
AWT layout managers are the FlowLayout, BorderLayout, GridLayout,
GridBagLayout and CardLayout classes. You can also implement your own custom layout
manager derived from the LayoutManager interface.
A container specifies which layout manager to use by calling the setLayout() method. This
can specify an instance of a layout manager or null, which means that no layout manager is
required. Components are then added to the container using the add() method. Thereafter, the
precise layout of the components is determined by the layout manager associated with the
component's container.
You can position components without using a layout manager, but this is unsuitable for applets and
other platform-independent programs, since the size of components can be different on different
platforms.
Noter til
Side 103 af 124
FlowLayout
Poul Henriksen 4
JAVA programmering
FlowLayout
Default layout for applet og
panel
Arrangerer komponenter I rækker
Fra venstre mod højre og fra top til bund
Justering er default Centrering for hver række (FlowLayout.CENTER
)
Justering kan specificeres vha. constructor
public void init() {
// change layout to flow, left aligned
setLayout(new FlowLayout(FlowLayout.LEFT));
add(new Label("Name"));
add(nameField = new TextField(12));
...
public void init() {
// change layout to flow, left aligned
setLayout(new FlowLayout(
FlowLayout
.LEFT));
add(new Label("Name"));
add(nameField = new TextField(12));
...
The FlowLayout manager is the default for panels, and therefore, applets. It simply lays out
components from left to right and from top to bottom. By default, components are centered within
their row, but when creating a new FlowLayout manger object, is possible to to specify left or
right alignment to the constructor.
BorderLayout
Poul Henriksen 5
JAVA programmering
BorderLayout
Default layout for frames og dialogs
Arrangerer komponenter I fire grænseområder og I
centrum
Opdeler container I 5 områder
Grænseområderne udlægges først
North og South tager fuld bredde
Hvis en container resizes, er det kun Center
der påvirkes.
Region specificeres når komponent tilføjes
North
South
West EastCenter
public void init() {
// change layout to border
setLayout(new BorderLayout());
add("West", colourChoice = new Choice());
...
public void init() {
// change layout to border
setLayout(new BorderLayout());
add("West", colourChoice = new Choice());
...
The BorderLayout manager can handle up to five components, each of which will occupy a
designated region of the container: North, South, East, West or Center. The contained components
will be stretched to fill the container according to their preferred and minimum sizes. The North
and South components will be stretched to fit to the width of the container and given their preferred
height. The East and West components height will be stretched to fit between the North and South
components and given their preferred width. The Center component will be given the remaining
space.
Noter til
Side 104 af 124
Note that the add() method for the BorderLayout takes a String as its first argument which
must be set to either North, South, East, West or Center. It is up to you to make sure
that you use one of these pre-defined values correctly - the compiler only checks that the parameter
is a well-formed String.
The BorderLayout constructor can be given a vertical and horizontal gap, which inserts some
space between the components.
GridLayout
Poul Henriksen 6
JAVA programmering
GridLayout
Arranger komponenterne I en netstruktur
Container opdeles I specificerede rækker og kolonner
Komponenter tilføjes fra venstre mod højre og fra top mod bund
Alle komponenterne har samme størrelse
Antal rækker og kolonnner skal specificeres til
constructor
public void init
() {
// change layout to grid of 4 rows x 3 cols
setLayout(new
GridLayout(4, 3));
add(new Button("1"));
add(new Button("2"));
...
public void init
() {
// change layout to grid of 4 rows x 3
cols
setLayout(new
GridLayout(4, 3));
add(new Button("1"));
add(new Button("2"));
...
The GridLayout manager divides a container into a grid of a specified number of rows and
columns. As components are added to the container, they are arranged in the cells of the grid in the
order in which they are added (i.e. left to right, and top to bottom). All the components will
therefore have the same size.
The GridBagLayout manager is more powerful, but much more complicated than the simple
GridLayout manager. Like the GridLayout manager, the container is divided into a grid of
rows and columns. However, as components are added to the container, adjacent cells may be
merged to accommodate the component, i.e. the components need not all be the same size. To
achieve this, each component must specify a number of "constraints" in a
GridBagConstraints object. Setting up these constraints is a complicated and time
consuming task which does not fit into the scope of this chapter. For further information, please
refer to the JDK documentation.
Noter til
Side 105 af 124
Brug Panels til at forbedre Layoutet
Poul Henriksen 7
JAVA programmering
Brug
Panels til at forbedre Layoutet
Det er ofte vanskeligt, at
opnå et
godt
layout, hvis der
kun anvendes en enkelt layout manager
Container kan ofte med fordel opdeles I mindre paneler
Panel klassen er blot en anden type container
Hver
panel kan have en forskellig type layout manager
Default layout for et panel er flow layout
Eksempel: layout knapper I bunden af en applet
public void init() {
setLayout(new BorderLayout());
Panel p = new Panel();
// add buttons to panel
p.add(new Button("OK"));
p.add(new Button("Cancel"));
// add panel to South area of applet
add("South", p);
. . .
public void init() {
setLayout(new BorderLayout());
Panel p = new Panel();
// add buttons to panel
p.add(new Button("OK"));
p.add(new Button("Cancel"));
// add panel to South area of applet
add("South", p);
. . .
The Panel class is a general-purpose type of container that can be used to hold other components.
Panels are very useful for improving the layout of a container. Incidentally, the Applet class
extends the Panel subclass with special hooks, which allow an applet to run in a browser or other
applet viewer.
From the Container class, the Panel class inherits the hooks for layout management, which
determine the position/size of each of its components, and the ability to manage groups of
components. For instance, to add a component to a panel, use one of the overloaded versions of the
add() method. Note that the default layout manager for a Panel object is the FlowLayout
layout manager.
Noter til
Side 106 af 124
Kapitel 11 Observer og Observable
Design pattern
Poul Henriksen 1
JAVA programmering
Observer og observable
Design pattern :
ideen bag D.P. er at indsamle og formalisere imitering.
Et godt velafprøvet mønster kan bruges i lignende situationer.
Observer/observable pattern
Problem : hvordan et vilkårligt antal (observer) objekter kan holde øje
med ændringer i et eller flere (observable) objekter.
Objekterne er løst koblede.
The model-view paradigm is common in object-oriented programming. The approach divides a
program into data-models and views on those models. The views must be informed of changes in
the model.
An inefficient approach to implementing this model is to use a polling loop -i.e. the views could
repeatedly check the model to establish if a change has taken place. A better approach is to have the
model contact the views when a change occurs.
The model must know which views it should contact in response to the occurrence of particular
events. This is achieved by allowing views to register with a model. Each view registers an
interest in the state of certain models, and is notified by those models when a state change takes
place.
An implementation of the registration and notification process must address certain issues - how
should the model contact the views and inform them of the change which has taken place. A
communication protocol is required. Java uses interfaces to solve this problem and provide a
protocol for communication. Views are only permitted to register with the model if they implement
a specified interface. The interface defines methods which the model can invoke on the registered
views to notify them of state changes.
Noter til
Side 107 af 124
Problem
Poul Henriksen
2
JAVA programmering
Problem
X,Y og Z ønsker at
blive informeret når der forekommer
bestemte ændringer I en datamodel
En løkke kan checke om der er sket ændringer, ineffektivt
Modellen skal
notificere de relevante observatører, når der
forekommer ændringer
Hvordan notificeres observatørerne
Må kende hvilke observatører der skal notificeres når der forekommer
ændringer
have en protokol til at kontakte observatørerne
Løsning
Modellen tilbyder metoder til registrering af observatører som h
ar
interesse I ændringer I modellen
Observatørerne kan kun blive registreret,
hvis de
kan kontaktes ved
brug af en etableret protokol
Eksempel på Observer og Observable
Poul Henriksen 3
JAVA programmering
Eksempel: Observer og Observable
Hver observer skal implementere interfacet java.util.Observer
Definerer en enkelt metode update()
Interfacet tilbyder en protokol for registrering og notificering
Det der skal observeres skal være en subklasse af
java.util.Observable
Registrerer observers hvis de implementerer Observer interfacet
Notificerer registerede objekter ved at kalde deres update() metode
View X
implements
Observer
Model
extends
Observable
View Y
implements
Observer
addObserver()
update()
View Z
implements
Observer
addObserver()
update()
addObserver()
update()
Public class Observable{
public void addObserver( Observer o){
// register o
}
. . .
Public class Observable{
public void addObserver( Observer o){
// register o
}
. . .
The package java.util provides a class called Observable, and an interface called Observer, to help
construct the model-view relationship. Each model or data object is an extension of the Observable
class. Each view is an implementation of the Observer interface. The Observer interface forms the
basis of a protocol for the registration and notification process.
(1) Registration:
The Observable class provides the methods addObserver() and deleteObserver(), which each take a
single parameter of type Observer. These methods allow Observer objects to register or de-register
their interest in an Observable model. Through this registration process the model is able to
maintain a list or registered views which are to be notified when a change occurs.
(2) Change and Notification:
Noter til
Side 108 af 124
Each Observable has a public method, notifyObservers(), which is used to request that all registered
observers be notified if there has been a change within the model. This method takes an optional
argument of type Object which can hold data that is to be delivered to the observers.
Each Observable keeps a flag to mark if a change has occurred within it. The flag is set using the
method setChanged(). The notifyObservers() method checks that this flag hasChanged() before
notifying the observers, and afterwards clears the flag by calling clearChanged().
Inside notifyObservers(), the update() method is called on each registered Observer. All observers
are sure to have an update() method since this is the one method declared by the Observer interface.
The arguments to update() are: first, a reference to the Observable object which changed, and
second, an argument of type Object which can be set to null or hold data concerning the change.
Implementering
Poul Henriksen 4
JAVA programmering
Implementering
Observer : Alle interessede objekter
Implementering af observer interfacet
Interface metode :
Public void update( Observable o, Object arg)
O det objekt der observeres på
Arg et argument overført fra Observable til beskrivelse af hændelsen
Observable : Objekt der skal observeres
Subklasse af observable
Vedligeholder en liste af observer objekter
r der indtræder en hændelse i objektet kaldes observable klassens
NotyfyObservers, som kalder hver enkelt Observer objekts Update metode
Centrale metoder i Observable :
Public void notifyObservers()
Kalder de registrerede Observer objekters Update metode
Public void addObserver(Observer 0)
Tilføjer en observer til observerlistern.
Protected void setChanged()
Markerer at dette objekt er blevet ændret.
Eksempler
Poul Henriksen 5
JAVA programmering
Eksempler
Observer.java eller s. 468+469 i JPL
ller
Noter til
Side 109 af 124
Eksempel på Observer og Observable
/**
* Gruppe nr. 1 */
import java.util.Observer;
import java.util.Observable;
import java.util.*;
/** holder styr på de enkelte køer */
public class FEntry extends Observable
{
private Feature f;
private Position p;
private boolean b;
private int ski ;
private int tæl;
public Feature getFeat()
{
return f;
}
public Position getPos()
{
return p;
}
public FEntry(Feature f)
{
this.f = f;
ski = 0;
tæl = 0;
}
public FEntry(Feature f, Position p, boolean b)
{
this(f);
this.p = p;
this.b = b;
}
public synchronized void enter()
{
ski = ski + 1;
notify();
this.setChanged();
this.notifyObservers(new Integer(this.getSki()));
}
Noter til
Side 110 af 124
public synchronized void remove()throws InterruptedException
{
if(ski <= 0)
wait();
ski = ski - 1;
this.setChanged();
this.notifyObservers(new Integer(this.getSki()));
}
public int getTæl()
{
return tæl;
}
public void putTæl(int tal)
{
tæl=tæl+tal;
}
public void putSki(int tal)
{
ski=ski-tal;
}
public int getSki()
{
return ski;
}
public boolean getBool()
{
if(ski > 0)
return (true);
else
return (false);
}
}
/**
* Gruppe nr. 1 */
import java.util.Observer;
import java.util.Observable;
public class Statestik implements Observer
{
private int tal = 0;
private int max = 0;
Noter til
Side 111 af 124
Statestik(Observable kilde)
{
kilde.addObserver(this);
}
public void update(Observable kilde, Object tilstand)
{
Integer tal = (Integer)tilstand;
this.tal = tal.intValue();
}
public int getStatestik()
{
if (tal > max)
{
max = tal;
return max;
}
else
return max;
}
/** nulstiller statestik */
public void Reset()
{
max = 0;
}
/** returnerer statestikken. */
public int getStatestik1()
{
return tal;
}
}
Noter til
Side 112 af 124
Kapitel 12 Collection Framework
Poul Henriksen JAVA programmering 1
Collection Framework
Collection er en samling af ensartede dataelementer organiseret i et
objekt, med tilhørende operationer til at virke p
å dataelementerne.
Collection framework består af :
-Interfaces
-Implementationer
Konkrete implementeringer
Genbrugebar datastrukturer
-
Algoritmer
Metoder der laver brugbare opgaver på Collections
Eks. Søgning, sortering
Genbrugbarer funktionallitet
Collection Framework ligger i java
.
util
Fordele ved Collection
Poul Henriksen JAVA programmering 2
Fordele…
o Nemmere programmering
Ingen lowlevel implementering
o Øger program hastighed og kvalitet
Optimeret kode, testet kode
o Nemt at overføre mellem forskellige API’s
Fælles sprog
o Nemmere at l
ære
Principperne går igen
o Nemmere at designe nye API
Behøves ikke at genopfinde hjulet
o Maner til SW genbrug
Noter til
Side 113 af 124
Sammenhængen mellem interfaces i Collection
Beskrivelse af de forskellige Interfaces
Poul Henriksen JAVA programmering 4
Interfaces
Collection :
De grundlæggende fælles metoder.
Ingen direkte implementeringer.
Set :
Ingen gentagne elementer. Indsætningsrækkefølge huskes ikke
List :
En ordnet collection. Kan indeholde gentagne elementer.
Indsætningsrækkefølge huskes.
Map :
Mapper nøgler til værdier
SortedSet
En sorterede udgave af Set
Elementer sorteret i stigende orden
SortedMap
En sorteret udgaver af Map. Sorteret efter glværdi (stigende orden)
Noter til
Side 114 af 124
Formålet med Interface Collection(Abstrakt)
Poul Henriksen JAVA programmering
6
Interface Collection
Repræsenterer en gruppe af objekter kaldet dets elementer
Primære formål : at overfø
re collectionsobjects
, hvor
maximun generalitet ønskes. Laveste fællesnævner.
De feste subinterfaces har construcrorer der modtager en
collection og omdanner det til et set eller list eller andet.
Collection c;
List l = new ArrayList(c); //skaber en ny arrayList
Metoder i Collection Interface
Poul Henriksen JAVA programmering 7
Collection Interface
public interface Collection
{ // Basic Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element); //
Optional
boolean remove(Object element); // Optional
Iterator iterator();
// Bulk Operations
boolean containsAll(Collection c);
boolean addAll(Collection c); //
Optional
boolean removeAll(Collection c); // Optional
boolean retainAll(Collection c); // Optional
void clear(); // Optional
// Array Operations
Object[] toArray();
Object[] toArray(Object a[]);
}
Noter til
Side 115 af 124
Metoder og eksempel på Iterator interface
Poul Henriksen JAVA programmering
8
Iterator interface
Metoder :
Boolean hasNext() true, hvis der er flere elementer i Collection
Object Next() returnerer næste object
Void remove() fjerner aktuelle
object fra
collection
Eksempel
static void filter(Collection c)
{
for (Iterator i = c.iterator(); i.hasNext(); )
if (!cond(i.next())) i.remove();
}
Er polymorf, virker for alle af typen Collection
Metoder i List Interface
Poul Henriksen JAVA programmering 9
List Interface
public interface List extends Collection
{ // Positional Access
Object get(int index
);
Object set(int index, Object element); // Optional
void add(int index, Object element); //
Optional
Object remove(int index); //
Optional
abstract boolean addAll(int index, Collection c); //
Optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator listIterator
();
ListIterator listIterator(int index);
// Range-view
List subList(int from, int to);
}
Noter til
Side 116 af 124
Oplysninger om List Interface
Poul Henriksen JAVA programmering
11
List Interface
Arver fra Collection.
List har rækkefølge.
Faste nummerede pladser
To generelle implementeringer af Lists :
ArrayList
LinkedList
Metoder i ListIterator Interface
Poul Henriksen JAVA programmering 12
Interface ListIterator
Arver fra Iterator (arver 3 metoder)
Kan traversere listen i begge retninger.
public interface ListIterator extends Iterator
{ boolean hasNext();
Object next();
boolean hasPrevious();
Object previous
();
int nextIndex();
int previousIndex();
void remove(); // Optional
void set(Object o); //
Optional
void add(Object
o); // Optional
}
Noter til
Side 117 af 124
Hvor er Interfacene Implementeret
Valg af implementering
Poul Henriksen JAVA programmering 14
Valg af implementering
SET
Hashset
hurtig, ingen orden
Skal specificere en kapacitetsfaktor
Set s = new HashSet(17)
TreeSet
Muliggør in-order
traversering
LIST
ArrayList
Skal ikke allokere nye noder
LinkedList
God hvis man ofte sætter ind forrest
MAP Har implementeringer der svarer til SET
Noter til
Side 118 af 124
Algoritmer fra klassen CollectionS
Poul Henriksen JAVA programmering
15
Algoritmer
public class Collections extends Object
Bemærk forskellen ml. Interfacet Collection og klassen Collections
Algoritmer til søgning, sortering m.m på Collection
Static metoder.
Er polymorfe algoritmer der opererer på collection
.
returnerer en ny Collection.
Uddrag af metoder i CollectionS
Poul Henriksen JAVA programmering 16
Uddrag af metoder i Collections
static intbinarySearch(List list, Object key
)
Searches the specified
list for the specified object using the binary search algorithm.
static intbinarySearch(List list,
Object key, Comparator c)
Searches the specified list for
the specified object using the binary search algorithm.
static voidcopy(List dest, List src
)
Copies all of the elements from one
list into another.
static voidfill(List list, Object o)
Replaces all of the elements
of the specified list with the specified element.
static Objectmax(Collection coll)
Returns the maximum element of the
given collection, according to the natural ordering
of its elements.
static Objectmax(Collection coll,
Comparator comp)
Returns the maximum element of the given collection, according to the order induced by
the specified comparator.
static Objectmin(Collection coll)
Returns the minimum element of the given collection, according to the natural ordering
of its elements.
Noter til
Side 119 af 124
Soterings orden (Comparable/Comperator)
Poul Henriksen JAVA programmering
17
Sorterings orden
Mange af metoderne i Collections baserer sig på en sorteringsorden.
Er defineret ved, at objekterne i Collection implementerer interfacet
Comparable eller
Comparator.
Comparable
Ligger i java.lang.Comparable
Metode : Public int compareTo(Object 0)
De fleste typer : String, Integer m.m. i
mplementerer Comparable
interfacet.
Comparable implementeres i egne klasser.
OH Implementering af Comparable s. 107
Comparator
nogle metoder i Collections benytter sig af Comparator som en ekstra
parameter
Comparator skal implementeres i en selvstæ
ndig klasse
Metode : Public
int compare(Object o1, Object o2 )
Noter til
Side 120 af 124
Kapitel 13 Streams og IO
Fil klassen
Fil klassen
Et Filobjekt repræsentere en fil på disken
Med følgende metoder
Exists()
isFile()
canRead() m.m.
Opret Fil med FileOutputStream
Eksempel
File f = new File (”D:\\temp”, name);
if (!f.exists()) {
//
Opetter fil
FileOutputStream fos = new FileOutputStream(f);
fos.close();
}
f.delete(); //Sletter den igen
Fil klassen bruges til at lave en reference til en fil samt at forespørge på filen med de tilhørende
metoder. Filen bliver først oprettet når man åbner en output stream til den.
File I/O Streams
File I/O Streams
Sequential, stream-based file access
Bare en af en stor familie i streams
JAVA
App
File
FileInputStream
FileOutputStream
Streamsfamilien er meget omfattende, dette er stort set det vi har gennemgået.
Der vil ikke blive stillet spørgsmål til eksamen til dette.
Efterfølgende vil der være et eksempel på hvordan man bruger disse streams.
Noter til
Side 121 af 124
Eksempel på brug af Streams
FileInputStream
window1 = new FileDialog(this,"FileDialog");
window1.setMode(FileDialog.LOAD);
window1.show();
String file = window1.getFile();
if (file == null)
{
return;
}
String directory = window1.getDirectory();
File f = new File(directory, file);
String temp1 = " ";
final int EOF = -1;
try{
FileInputStream Indfil = new FileInputStream(file)
DataInputStream IndStroem = new DataInputStream(Indfil);
int Ind;
while ( (Ind = IndStroem.read()) != EOF)
temp1 = temp1 + (char)Ind;
output.append(temp1);
Indfil.close();
}catch(IOException ef){output.append("hvad prøver du på");}
}
FileOutputStream
window1 = new FileDialog(this,"FileDialog");
window1.setMode(FileDialog.SAVE);
window1.show();
String file = window1.getFile();
if (file == null)
{
return;
}
String directory = window1.getDirectory();
File f = new File(directory, file);
try{
FileOutputStream udfil = new FileOutputStream(file);
DataOutputStream udstrøm = new DataOutputStream(udfil);
String temp1 = " ";
for(int y = 0;y < 18;y++)
{
if (stik2[y]!=null) {
temp1 = temp1.concat(String.valueOf(stik2[y].getStatestik()));
Noter til
Side 122 af 124
}
else
temp1 = temp1.concat("0");
if (stik3[y]!=null)
temp1 = temp1.concat(String.valueOf(stik3[y].getStatestik()));
else
temp1 = temp1.concat("0");
if (stik1[y]!=null)
temp1 = temp1.concat(String.valueOf(stik1[y].getStatestik()));
else
temp1 = temp1.concat("0");
if (stik[y]!=null)
temp1 = temp1.concat(String.valueOf(stik[y].getStatestik()));
else
temp1 = temp1.concat("0");
}
for(int o = 0;o<temp1.length();o++)
udstrøm.write(temp1.charAt(o));
udfil.close();
}catch(IOException ef){output.append("hvad prøver du på");}
}
Begge eksempler er fra Gruppe 1´s projektopgave Skiing Appilkation.
Noter til
Side 123 af 124
Indeks
A
Abstrakte;38;39;40
Access;68
Adapter;98
Algoritmer;118
anonym;99
Applets;71;73;80;86
arv;26;28;36
Arv;26
AWT;72;76;86;87;88;89;90;91;92;94;95;9
6;101;102
B
BorderLayout;101;102;103;104
Button;65;81;82;87;89;91;93;94
C
catch;54;55;56;59;60;63;121;122
Collection;69;112;113;114
CollectionS;118
Comparable;119
Comperator;119
constructor;7;14;15;16;19;20;28;29;52;57;61;
69;73;78;87;90;103;104
Constructors;14;15;19;20
Container;72;86;94;101;105
Containers;101
D
Design;35;106
E
Event;41;89;92;93;95
Events;86;90;91;92;95;97
exceptions;52;53;55;56;57;58;59;60;61;62
Exceptions;52;59;60
extends;27;36;44;45;50;62;81;90;99;105;109
F
farve;78
Fil;120
Final;23;33
Finalize();69
Finally;18;56;73
FlowLayout;101;102;103;105
Fonten;77
former;79
Framework;112
G
Garbage;69
Graphics;74;76;77;78;79;83;96
GridLayout;101;102;104
H
hiraki;27
I
Importering;66
Indkapsling;13
input;88
Instanse;12
Interface;41;42;45;92;114;115;116
interfaces;23;27;38;41;42;85;89;95;96;97;98;
106;113
Interfaces;34;41;43;92;95;113
IO;120
Item;96
Iterator;115
J
JAVA-UI;85
K
klasse;10;22;99
komponenter;85;86
kontrol;32
L
Label;87
Layout;102
linier;79
List;91;115;116
Listener;92;95;96;97
ListIterator;116
livscyklus;73
Noter til
Side 124 af 124
M
Metode;11
metoder;17;18;21;22;30;40;48;58;118;120
Metoder;12;114;115;116
modifiers;11
Mouse;95;96
N
Notificering;93
O
Object;5;27;29;34;37;44;45;46;49;90;94;108;
111
Observable;106;107;108;109;110;111
Observer;106;107;108;109;110
Overloading;16;19
Overriding;29
P
package;10;64;65;66;67;68;90;97;98;107
Packages;64;65;94
Panels;105
Polymorfi;40;43
Polymorphisme;32
R
referencer;18
S
Semantik;28
Sikkerhed;80
skjulte;30
static;20;21;23;24;25;31;37;42;46;63;81
Streams;120;121
String;15;19;23;24;25;31;34;36;37;45;46;4
7;48;49;50;51;63;74;76;90;104;121;122
StringBuffer;47;48;49;50
Subklasser;26
superklassens;30
T
Tegne;77
this;5;6;8;9;12;13;14;15;16;17;18;19;21;22;2
3;24;26;29;30;31;33;36;37;38;39;40;47;48;
50;52;56;57;58;59;60;61;62;64;65;67;68;6
9;72;73;74;75;76;77;81;82;83;85;86;87;88;
92;93;94;97;98;99;102;104;106;107;108;10
9;110;111;121
this-Referencen;15
Throwable;54;55;60;61
Throwing;60
toString();36;37;46;49;61;90
try;35;54;56;59;63;66;121
type;14;16;17;19;29;31;32;33;35;43;47;49;50
;51;52;60;76;89;90;91;92;93;94;105;107;1
08
U
Udskiftning;31
V
variable;8;9;11;13;15;16;17;18;20;22;23;31;6
6;67;90;94;96;99
variabler;20;23;30
Værdioverførsel;17
W
Wrapper;50