Introduction to Computer Science I
Download
Report
Transcript Introduction to Computer Science I
Technische Universität Darmstadt
Telecooperation/RBG
Introduction to Computer Science I
Topic 11: Introduction to OOP with Java:
Classes and Object
Prof. Dr. Max Mühlhäuser
Dr. Guido Rößling
Copyrighted material; for TUD student use only
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Lecture Outline
• Object-oriented design in a nutshell; classes and objects
in Java
• Interpreters, compilers, virtual machines; Java compile
and runtime environment
• Visibility of variables in Java
• Packages
• Introduction to testing Java classes with Eclipse and JUnit
Introduction to Computer Science I: T12
2
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Object-oriented programming (OOP)
• OOP: one of the existing programming paradigms
• Other paradigms: functional programming, logic
programming
• OOP models “the world” as a set of cooperating objects,
where:
– Each object is responsible for a well-defined part of the overall
computation
• Encapsulates the definition of the data needed for this part
of the computation and of operations that process this data
• Can use services of other known objects to perform the
computation
– Each object is an instance of a class
– Classes are organized in an inheritance hierarchy
• Class hierarchies correspond to concept hierarchies in the
application domain to be modeled
Introduction to Computer Science I: T12
3
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Object-Oriented Programming (OOP)
• Initial example: writing software for the real estate company
Fine&Expensive, which manages and rents exclusive houses
• Objects will represent houses, employees, and clients
– For each house, we need to store information about the
managing employee, the owner, number of bedrooms, etc.
– For each client, we need to manage the number of houses (s)he
has for rent, the name, phone number, etc.
– Employees have a name, phone number, list of managed houses,
…
– …
• Different types of houses will be modeled as heirs of a class
that captures what all houses have in common
– One-family house, multifamily residence
Introduction to Computer Science I: T12
4
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Object-Oriented Programming (OOP)
©
Important
The world of
Fine&Expensive
Miller
manages
Smith
ownedBy
Rich
Introduction to Computer Science I: T12
5
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Object-Oriented Programming (OOP)
Object
The world of real
estate companies
Ur_Object Type
Person
responsible
for
2..10
Employee
Manager
©
owns
Client
* House
0..2
One-family
house
Multifamilyresidence
HouseManager manages
Concepts &
Categorization
Introduction to Computer Science I: T12
6
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Object-Oriented Programming (OOP)
Object
The world of
rental companies
Person
responsible
for
2..10
Employee
Manager
©
owns
Client
A concrete
instantiation
* House
0..2
One-family
house
Multifamilyresidence
HouseManager manages
Introduction to Computer Science I: T12
7
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Classes and Constructor Operations
• In general, a class describes the common aspects of
a group of objects (instances) that share
– the same set of properties (attributes)
– the same behavior (operations)
Data
(Variables)
Blueprint (template) for objects;
describes their structure and
services
Introduction to Computer Science I: T12
8
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Classes in Java
<ClassDefinition> =
class Class-Name [extends SuperClassName]
<ClassDefinitionBlock>
<ClassDefinitionBlock> =
{ <MemberDefinition> ... <MemberDefinition> }
<MemberDefinition> = <FieldDeclaration>
| <OperationDefinitons>
| <ConstructorDefinitions>
• The definition block of a class consists of
– a set of variable declarations
• also called attributes, instance variables, fields
– a set of operation definitions
– constructor definitions
Introduction to Computer Science I: T12
9
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Attributes (Instance Variables, Fields)
• Attributes are variables that model properties of an object (that is
why they are called instance variables)
– Current value of a counter, current balance of an account…
• Attribute variables have a name, a type and a value
– The name is mostly written in lower case
– Attribute values change during program execution
Remember: int is a
primitive type in Java.
It represents the class of
natural numbers between
-2,147,483,648 and
2,147,483,647
(define (make-counter)
(local (
(define currentVal 10)
...
)
class Counter { name
int currentVal;
...
type
}
class Counter {
int currentVal = 10;
...
}
value
Introduction to Computer Science I: T12
10
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Constructor Operations
• Each class defines so-called constructors
• A constructor defines, by means of its parameters, generic
initialization instructions
• In Java, constructors are special operations that have
– the same name as the class
– no return value
formal parameter of
the constructor
class Counter {
int currentVal;
attributes are initialized
...
with values of the actual
Counter(int initVal) {
parameters of the
currentVal = initVal;
constructor call
}
(define (make-counter initVal)
...
(local (
(define currentVal initVal)
...
}
)
Introduction to Computer Science I: T12
11
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Constructor Operations
• Initialization instructions are defined in a class
once and used multiple times
– Creation of multiple counter instances of the
same type with differently initialized attributes
keyword for the creation
of object instances
...
Counter c1 = new Counter(3);
Counter c2 = new Counter(6);
...
...
(define c1 (make-counter 3))
(define c2 (make-counter 6))
...
Introduction to Computer Science I: T12
12
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Java Class Counter
class Counter {
int currentVal;
public Counter(int initVal) { currentVal = initVal; }
Visible
outside the
body of
Counter
/**
* Effect: Increases the current value of counter by 1
*/
public int inc() {
currentVal = currentVal + 1;
return currentVal;
}
/**
* Effect: Decreases the current value of counter by 1
*/
public int dec() {
currentVal = currentVal - 1;
return currentVal;
}
JavaDoc comment.
Abbreviated due to
lack of space on
slide.
/**
* @return the current value of the counter
*/
public int getCurrentVal() {
return currentVal;
}
}
Introduction to Computer Science I: T12
13
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Classes in Scheme and Java
• Scheme classes are modeled by constructor functions
(make-XXX)
– Play at the same time the role of Java constructors
– Return dispatcher functions:
• Combine and hide all service functions the only service visible
from the outside is the dispatcher
• Java provides a special form for class definitions
– Classes are no first-class values cannot be passed as
parameters or returned from functions
– A class can have multiple initialization instructions
– The dispatch mechanism is an implicit language feature
• the dispatcher is part of the Java semantics and does not need to
be programmed (more on dispatching operation calls in the next
lecture)
Introduction to Computer Science I: T12
14
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Class Interfaces in Scheme and Java
• Scheme’s service managers (dispatchers) are interface
functions:
– map symbols to functions of different types
An address-book is an interface:
'add :: symbol number -> void
'search :: symbol -> number
• The interface of a Java class results from the set of
operations that are declared public…
– All non-public operations are invisible from the
outside
• For now, we say that they can only be called from
(public) operations of the same class
• Not quite true; will reconsider later
• The concept of an interface as a function that binds
symbols to operations with a different contracts
remains valid…
Introduction to Computer Science I: T12
15
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Encapsulation in Java (Information Hiding)
class Counter {
int currentVal;
...
}
The attributes of an object are generally invisible outside a
class definition. Their values can be accessed only within the
methods implementing the operations in the interface of a
type.
Non-public operations are also encapsulated.
...
Counter c1 = new Counter(2);
int current = c1.currentVal;
int current = c1.getCurrentVal(); // OK
...
Introduction to Computer Science I: T12
16
©
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Encapsulation (Information Hiding)
• General design idea: the process of hiding details of some
program module (e.g., class or function)
• Powerful idea: reduces the complexity of the application
– No need to understand the hidden details in order to use some
module
– Reduces coupling between modules
– Can change hidden implementation details without invalidating
clients
– Module interface as contract
• We have already seen this design idea
– data abstraction: hide representation
of data type
– Make-functions hide local definitions of objects
Introduction to Computer Science I: T12
17
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Encapsulation and Abstraction
• Idea: combining elements to create a larger entity
that can be used as a primitive one in the next step,
thereby hiding the details of the composition
• Encapsulation is a mechanism to hide information
• Term sometimes used in a more general sense
– As a synonym for information hiding
• Term sometimes used in a more specific (OO) sense
– Meaning “data and operations together”
Introduction to Computer Science I: T12
18
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Classes as a two-fold abstraction
• … describe only those
attributes and services
of real objects that are
relevant for the
software to model
• A class definition ignores irrelevant differences
between all possible elements (objects) of a class
• The class Counter ignores possible differences in
the current value of the individual counters of
this type
Introduction to Computer Science I: T12
19
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Classes & Objects
• Classes in Java are static descriptions ("on paper",
respectively: "in the file") "blueprints"
• Objects are run-time entities of a program values
– dynamic (are kept in the main memory of the computer
during run-time)
– There might be several objects of a class, each with its own
identity and state
– Can be accessed by means of a name
• Each object belongs to a class and knows its class
• A class does not (usually) know its objects
Introduction to Computer Science I: T12
20
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Characteristics of an Object
Introduction to Computer Science I: T12
21
Performing Computations
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
• Any computation in an OO program is the result
of invoking an operation on a previously created object
• Note the dot-notation for operation invocation
public class CounterConsumer {
Counter c1 = new Counter(3);
Counter c2 = new Counter(6);
(begin
(inc
(inc
(dec
public void doSomethingWithCounters() {
c1.inc();
c1)
c1.inc();
c1)
c1.dec();
c1))
System.out.println(c1.getCurrentVal());
(getCurrentVal c1)
(begin
(inc c2)
(dec c2))
c2.inc();
c2.dec();
System.out.println(c2.getCurrentVal());
}
}
(getCurrentVal c2)
Introduction to Computer Science I: T12
22
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Performing Computations
• The task is divided into service instructions
– Formulated as messages (operation invocations) to objects
• Each message contains:
– Name of the receiver object: c1 in the example
– Name of the service (operation) that the receiver shall
execute
• inc(), dec(), ...
• The operation must be contained in the receiver's interface
• Only one message is sent at any point in time
• If there are multiple objects, they can send messages
to each other
– Delegate substasks to known objects
Introduction to Computer Science I: T12
23
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Remember: How Everything Begins...
There is a special method called main which is called
automatically when a Java program is run…
public class CounterTest {
// ...
public static void main(String[] args) {
CounterConsumer cc = new CounterConsumer();
cc.doSomething ();
}
// ...
CounterTest.java
}
Java
Compiler
Java Bytecode
Interpreter
javac CounterTest.java
java
CounterTest
Introduction to Computer Science I: T12
24
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Lecture Outline
• Object-oriented design in a nutshell; classes
and objects in Java
• Interpreters, compilers, virtual machines; Java
compile and runtime environment
• Visibility of variables in Java
• Packages
• Introduction to testing Java classes with
Eclipse and JUnit
Introduction to Computer Science I: T12
25
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Interpreter
• We have seen that an interpreter is a program that
directly executes another program written in a
certain programming language
• Operation mode of interpreters. Let inpExp be the
next expression to be executed in the input program:
1. Perform a syntactic analysis of inpExp
2. Map inpExp to an expression (sequence) outExp
in the machine language, or the language of the
interpreter itself (meta-circular interpreter)
3. Execute outExp
4. Repeat steps 1 to 3 for the next expression in the
input program following inpExp
Introduction to Computer Science I: T12
26
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Compiler
©
Program in
language A
Program in
language B
compiler
source
program P1
A source language
B target language
target
program P2
• Semantic correctness:
– Every program P1 in A corresponds to exactly one program P2
in B
– The destination program P2 must have the same meaning
(semantics) as P1
Introduction to Computer Science I: T12
execution
• A compiler is a program that translates programs from
a source language A to a target language B
27
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Compiler
Rear Admiral Grace Murray Hopper (1906 – 1992)
She invented the compiler, she
said, because she was lazy and
hoped that "the programmer
may return back to being a
mathematician."
Introduction to Computer Science I: T12
28
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Stages of Compilation
Lexical Analysis
Source code gets chopped into a
sequence of terminals
(tokens, words)
Syntactic Analysis
Tests if the source code conforms to the
syntactical rules of the source language.
Organizes terminal symbols in valid
sentences.
Semantic Analysis
Tests if all names used in the source are
declared and then used according to their
types.
Code Generation
Target program is generated
Introduction to Computer Science I: T12
29
Traditional Compilation
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
source program in language A
Compiler for
language A and
processor X
Executable program
(binary code) for
processor X
Compiler for
language A and
processor Y
Executable program
(binary code) for
processor Y
N Languages
Pascal
Compiler for
language A and
processor Z
Executable program
(binary code) for
processor Z
N*M Compilers
M Platforms
Linux
Smalltalk
Java
Prolog
Windows
MacOS
C++
Introduction to Computer Science I: T12
30
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Advantages and Disadvantages of Interpreters
- Advantage: Good support of the testing/prototyping
stage of the program fast prototyping
- Changed expressions / declarations of the source code
directly executable
- Retranslation of the program not necessary
• Disadvantage: executing takes longer
• If expressions are used k times in the source code (e.g., in
loops), they are analysed and dispatched k times
• For each access of the same variable in different locations
in the program, the respective address must be
determined over and over again
Introduction to Computer Science I: T12
31
©
Advantages and Disadvantages
of Traditional Compilation
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
• Advantage: Optimal utilization of the processor properties
– Very fast execution of the compiled programs
• Disadvantage: A program that is written in a higher-level
programming language can theoretically run on every
machine after being compiled with the appropriate
compiler
„The difference between theory and
practice is that in theory, there is no
difference between theory and practice,
but in practice there is.“
Introduction to Computer Science I: T12
32
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Drawbacks of Traditional Compilation
• The compiled program runs only on one processor type or
operating system
• It must be compiled with a different compiler for each
processor type or operating system
– Windows on PC != Linux on PC
• Programming languages are often defined in a platform
dependent way
– Specific properties of the machine affect the design of
the compiler
• E.g., the size of registers or memory cells which in turn affect the
maximal length of the numbers that can be manipulated
– Consequence: There are often different dialects of a
programming language
Introduction to Computer Science I: T12
33
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Virtual Machines (VM)
• A virtual machine is a program (software) that
simulates a hardware processor
• Programs in a higher programming language (e.g.,
Java) are compiled into the intermediate language
– The simulated hardware processor has a set of assemblerlike instructions that it understands and a set of software
registers
– The instructions of the intermediate language are often
called byte code
• The VM serves as an interpreter for this assemblerlike intermediate language
• A VM hides the specific properties of a certain
processor type adds a new abstraction layer on
top of hardware!
Introduction to Computer Science I: T12
34
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Virtual Machines (VM)
N Languages
Pascal
Smalltalk
N + M Compilers
M Platforms
Linux
Virtual
Machine
Windows
Java
Prolog
MacOS
C++
Introduction to Computer Science I: T12
35
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Advantages and Disadvantages of VMs
• Advantages: compiled programs run on all processor
types or OS for which there exists a VM
• Only one compiler is needed for all processor types or
operating systems
• The higher-level language becomes independent of
different hardware platforms or OS
• Of course, you need one VM per processor and OS
• Disadvantages: byte-code programs are slower than
machine programs
• Solution: just-in-time-compiler compiles bytecode to an executable program for a specific
processor type / OS
• When the code is loaded or the first time the
instructions are executed
Introduction to Computer Science I: T12
36
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Java Compilation und Runtime Environment
Introduction to Computer Science I: T12
37
©
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Structure of a Java Program
• A Java program consists of an arbitrary number of classes,
at least one of which must contain the main operation
• Responsibility of the main operation:
– Object creation the construction of an initial minimal set of
objects
– Calling the first operation
– In general, it should not contain further control flow of the Java
program
• The real control flow is encapsulated within the implementation of
the operations of cooperating objects
– Remember that computations are organized by multiple
cooperating objects, and each object covers only a small sub-task
• The main operation will be started and executed by
means of the Java interpreter
Introduction to Computer Science I: T12
38
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Java Runtime Environment
• Java Interpreter: program for executing Java byte codes on a
particular machine
• Just-In-Time Compiler (JIT-Compiler) :
– After being loaded, a class can (optimally) be directly translated
into the machine code of the particular machine
– If the Java installation at hand does not have a JIT compiler, the
byte code will be directly executed by the Java interpreter
• Runtime System: provides important resources to Java
program irrelevant to this course
• Byte code-Verifier: verifies that the loaded byte codes satisfy
the JVM specification
– Classes can be loaded from the Internet or from the local file
system at the runtime of a Java application
– Part of the security provisions are performed by the verifier
Introduction to Computer Science I: T12
39
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Java Compilation (Repeated)
• Java compiler
– Input: Java source file, SomeFile.java, that contains one
or more class definitions
• Such a file is called compilation unit
– Output: for each class Cl in SomeFile.java, the compiler
will generate exactly one file Cl.class that contains the
bytecode for the class Cl
SomeFile.java
Java Compiler
class Cl1 {...}
class Cl2 {...}
class Cl3 {...}
Introduction to Computer Science I: T12
Cl1.class
Cl2.class
Cl3.class
40
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Lecture Outline
• Object-oriented design in a nutshell; classes and objects in
Java
• Interpreters, compilers, virtual machines; Java compile
and runtime environment
• Visibility of variables in Java
• Packages
• Introduction to testing Java classes with Eclipse and JUnit
Introduction to Computer Science I: T12
41
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Variable Visibility within a Java Class
•
As in Scheme, a name may be used multiple times for different
purposes, e.g., as an instance variable, a parameter, a local
variable
•
Similar to Scheme, Java employs lexical scoping: inner
declarations have precedence over outer declarations
–
–
–
•
Outer declarations are not directly accessible anymore
Using this.<attribute name> one may still access instance
variables
Local variables and parameters may not be re-declared
A re-declaration does not affect the existence of the outer variable
–
Invisibility does not imply non-existence; outside the re-declaring
block, the outer variable is visible again
Introduction to Computer Science I: T12
42
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Variable Visibility within a Java Class
class Example {
int i;
char c;
void g(int n) {
int i, j;
for (char c... ) {
int k;
… i … k … c … n … this.i …
}
… c …
}
}
Introduction to Computer Science I: T12
43
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Lecture Outline
• Object-oriented design in a nutshell; classes and objects in
Java
• Interpreters, compilers, virtual machines; Java compile
and runtime environment
• Visibility of variables in Java
• Packages
• Introduction to testing Java classes with Eclipse and JUnit
Introduction to Computer Science I: T12
44
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Packages
• Packages bundle up classes which belong together with
respect to an area of responsibility
• Help to avoid name conflicts
– Class names have to be unique (but only within a package)
Two or more classes may use the same (non-public) class
name, e.g., List
• Hide classes which only serve an internal purpose and
should not be visible from outside
Introduction to Computer Science I: T12
45
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Package Hierarchies
• Packages are organized hierarchically
A package may contain other packages
Which in turn can contain packages, etc.
• “Dot” notation for package names
package.subpackage.subsubpackage.Class
• The preamble of a .java file determines with which
package the following classes are associated
Introduction to Computer Science I: T12
46
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Package Naming Conventions
• Package name mirrors the Internet domain name of the
manufacturer in reverse order
• Slashes and “-” are not allowed
• Replace a dash by an underscore (or skip it)
– SUN domain: sun.com
SUN class: com.sun.p1.p2.X
– TUD domain: informatik.tu-darmstadt.de
TUD class:
de.tu_darmstadt.informatik.p1.X
• This convention helps to ensure world-wide unique class
names
Introduction to Computer Science I: T12
47
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Package Declaration
• The same package name may be used in several files
– One package may contain several files
Faster (re-)compilation
supports workload distribution in larger projects
• The full name of a class always includes the package
name (packagename.classname)
• Shortcut denotation using the class name only is possible
within the same package or when the respective
package or class has been imported
Introduction to Computer Science I: T12
48
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Structure of a Java file
<Source-File> ::= <Package-Declaration>
<Import-Declarations>
<Type-Definitions>
<Package-Declaration> ::= package <Package-name> ; | ε
<Package-Name> ::= <Identifier> {. <Package-Name>}
• Only comments or blank lines may be put before
package declarations
• Only one package name per file
• Without a package declaration, the contained classes
are associated with an anonymous default package
Introduction to Computer Science I: T12
49
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Package Import
<Import-Declarations> ::= { <Import-Declaration> | ε
<Import-Declaration>
::= import <Package-Name> "."
(<Class-Name> | "*") ";"
• Class definitions following the import statement may
then access the imported class(es) without specifying
the full name
• If "*" (wild card) is used, all classes contained in the
package may be accessed
• If you only want to import class methods (static), use
this notation:
import static <Package-Name>.<Class-Name>.<Methode>;
Introduction to Computer Science I: T12
50
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Using Packages
• Using full qualification
java.util.Random numberGenerator
= new java.util.Random();
• Using import
import java.util.Random;
...
Random numberGenerator = new Random();
Introduction to Computer Science I: T12
51
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Package Import
• Importing classes with the same name yields a name
conflict
import java.awt.*;
// contains class List
import java.util.*; // contains class List
// ...
java.util.List list; // use package name
// to pick one out
• Two packages are automatically imported
– the current package
– the predefined package java.lang containing basic classes
such as Object, String, etc.
Introduction to Computer Science I: T12
52
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Package Import
The Java library contains a number of predefined packages
(all part of the JDK)
– java.applet
applet support
– java.io
input/output, files
– java.net
network support
– java.util
utility types, e.g., container types
– java.util.zip support for .zip archives
– etc.
Introduction to Computer Science I: T12
53
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Package Naming
Package names and directory structures
• The location of the files defining a package mirrors the hierarchical
package structure
• Dots need to be replaced with
– UNIX
Slash “/”
– Windows Backslash “\”
Example
– package name: kilian.hobby.raytracer
– corresponding UNIX directory structure:
kilian/hobby/raytracer
Introduction to Computer Science I: T12
54
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Binding Packages
©
Packages and the "CLASSPATH"
• A package name is interpreted as a relative path
• The environment variable CLASSPATH contains all
directories which are to be searched for classes or
packages
• Alternatively, a CLASSPATH may also contain ZIP- or
JAR-archives, containing classes
• Example for UNIX
CLASSPATH=.:/home/joe/classes:/usr/classes.zip
current directory
separates directories
Introduction to Computer Science I: T12
55
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Binding Packages
Packages and the "CLASSPATH"
• The directories specified in the CLASSPATH are used as
starting points for the relative package name (used as
pathnames)
• Searching order is from left to right
• It is possible that one package name exists in two or
more existing directories
Not a good idea, as the selection of a package then
depends on the order of the paths in CLASSPATH
Introduction to Computer Science I: T12
56
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Lecture Outline
• Object-oriented design in a nutshell; classes and objects in
Java
• Interpreters, compilers, virtual machines; Java compile
and runtime environment
• Visibility of variables in Java
• Packages
• Introduction to testing Java classes with Eclipse and JUnit
Introduction to Computer Science I: T12
57
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Testing with JUnit and Eclipse
Test-first programming Our design recipes
require that we write tests before we start coding
JUnit is a program (framework) that automates parts of
the process of writing and running tests
• JUnit is already integrated into Eclipse
Poor kid, we should have told him to test, then code when he started
Introduction to Computer Science I: T12
58
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Motivation: JUnit
• Similarly to our test cases for Scheme, we also want to
be able to test our Java programs
• We write testing program code that uses sample data on
operations and evaluates the result.
– The testing program is developed and executed in parallel at
development time with the actual program
– Whenever we want to know if certain test cases still work
correct
We use a testing framework, here JUnit:
- for automated unit tests
Introduction to Computer Science I: T12
59
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Annotations
• Before we look at JUnit, let us take a look at
annotations
– The latest version of JUnit is implemented with annotations
• Annotations give metadata about code
• Java 1.5+ defines seven annotations
– It is possible to add user-defined annotations
– There are three “real” annotations…
– …and four “meta” annotations
• Annotations are marked in code with @-sign
– For example, @SuppressWarnings
• Annotations refer to the following element
– Element = line of code, method, …
Introduction to Computer Science I: T12
60
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
“Real” Annotations
• @Override
– Indicates that a method overrides a method in the base class
– Can be used to check for typos or errors in method signature
• @Deprecated
– Produces a compiler warning if the element is used
• @SuppressWarnings
– Turn off compiler warnings for the following element
Introduction to Computer Science I: T12
61
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Meta Annotations
• @Target(arg)
– Where can the annotation be used?
– Additional argument: CONSTRUCTOR, FIELD, LOCAL_VARIABLE,
METHOD, PACKAGE, PARAMETER, TYPE
• @Retention(arg)
– How long to keep annotation info?
• SOURCE = Discarded by compiler
• CLASS = Available in class-file, discarded at runtime
• RUNTIME = Retained by virtual machine for run-time use
• @Documented
– Include annotation in JavaDoc
• @Inherited
– Allow subclasses to inherit annotation
Introduction to Computer Science I: T12
62
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Annotations: Example
• Annotations @Target and @Retention can be used to
define new annotations
• New annotations are defined like interfaces and re-use
the keyword @interface (with the @ prefix!)
• Example:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
public int id();
public String description()
default "no description";
}
Introduction to Computer Science I: T12
63
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Annotations: Example
• Using previous annotations to define use cases
public class PasswordUtils {
@UseCase(id = 47, description =
"Password must have one number")
public boolean validatePassword() {
// validation code...
}
@UseCase(id = 48)
public String encryptPassword() {
// encryption code...
}
}
Introduction to Computer Science I: T12
64
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Annotations and JUnit
• The latest version of JUnit is based on annotations
• Test cases are marked with annotation @Test
• Earlier versions relied on specific naming conventions
for test classes; not needed anymore
• We will come back to JUnit in a moment…
• But first, a few more words about testing
Introduction to Computer Science I: T12
65
Test stages
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Development stages with corresponding Tests
Client
wishes
Acceptance Tests
System tests
Requirements
Design
Integration tests
Code
A
X
B
Y
Unit tests
A happens before B
X finds faults in Y
Introduction to Computer Science I: T12
66
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Test stages
In different stages, different test strategies are useful
• Unit Test: Test of code components, e.g. code of a method or a
class structural testing
• Integration test: Test of the integration of multiple code
components structural testing
• System test: Test of the whole system against the specification
functional testing
• Acceptance test: Test of the whole system with real data from the
client
Introduction to Computer Science I: T12
67
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Testing & Development Methodologies
©
An unwanted vicious circle…
time pressure
more
time
pressure
more
errors
less tests
Introduction to Computer Science I: T12
68
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
Testing & Development Methodologies:
“Agile” Methodologies
code a
little
•
•
•
©
test a
little
Development & testing as interleaved activities
Test case creation before code is written
Tool support required
Introduction to Computer Science I: T12
69
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Testing
• Testing is a necessity in real life
– The earlier faults are found, the better (and cheaper)
– Development usually is an iterative process with feedback loops
• If possible, do not only test for quality, but build for
quality
– Systematic Procedures Software Engineering
Introduction to Computer Science I: T12
70
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Testing with Junit 4.4
•
•
•
•
•
•
In the following, we will test a small calculator
The implementation of this class is rather easy
It will only work for int values
It is very simple and inefficient
It also has a couple of bugs
We will see how JUnit can help us track those bugs!
Introduction to Computer Science I: T12
71
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Calculator Class (Part I)
package calc;
public class Calculator {
private static int result;
// Static variable where the result is stored
public void add(int n) {
result = result + n;
}
public void substract(int n) {
result = result - 1;
//Bug : should be result = result - n
}
public void multiply(int n) { // not ready yet
}
public void divide(int n) {
result = result / n;
}
public void square(int n) {
result = n * n;
}
Introduction to Computer Science I: T12
72
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Calculator Class (Part II)
public void squareRoot(int n) { // will be implemented later…
for (; ;) ;
// Bug : loops indefinitely
}
public void clear() {
// Clears the result
result = 0;
}
public void switchOn() {
// Switch on the screen, display "hello", beep
// and do other things that calculator do nowadays
result = 0;
}
public void switchOff() {
// Display "bye bye", beep, switch off the screen
}
public int getResult() {
return result;
}
}
Introduction to Computer Science I: T12
73
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
How Do We Test A Calculator?
• We want to test each operation separately
–
–
–
–
–
•
•
•
•
Add
Substract
Divide
Multiply
Square Root – deferred for now (indefinite loop!)
We write one test method per test
The methods go into a separate class CalculatorTest
Tests are annotated with @Test before the “public”
We need to initialize the calculator before each test
– Need to send “clear()” to ensure the value is 0
– Otherwise, we get incorrect follow-up errors
Introduction to Computer Science I: T12
74
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The CalculatorTest Class (Part I)
package junit4demo;
Choose any package name here
This is our calculator code
import calc.Calculator;
import junit.framework.JUnit4TestAdapter;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
Several needed imports for JUnit
Import only this static
method from class Assert
/**
* Basic test class using @Test, @Before and @Ignore annotation
* as well as assert keyword and assertEqual methods
*/
public class CalculatorTest {
private static Calculator calculator = new Calculator();
// Used for backward compatibility (IDEs, Ant and JUnit 3 text runner)
public static junit.framework.Test suite() {
Needed for older
return new JUnit4TestAdapter(CalculatorTest.class);
environments
}
Introduction to Computer Science I: T12
75
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Calculator Test Class (Part II)
@Before
// must be public not protected like the setup
public void clearCalculator() {
calculator.clear();
}
//==================================
//
Test cases
//==================================
@Test
public void add() {
calculator.add(1);
calculator.add(1);
assertEquals(calculator.getResult(), 2);
}
@Before: run before each
test, so calculator starts
each test with value 0
@Test: this is a test method
that should be run. This will
assert that 1+1 = 2.
Introduction to Computer Science I: T12
76
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Calculator Test Class (Part III)
@Test
public void subtract() {
calculator.add(10);
calculator.substract(2);
assertEquals(calculator.getResult(), 8);
}
@Test
public void divide() {
calculator.add(8);
calculator.divide(2);
assertEquals(calculator.getResult(), 5);
}
This will assert that 10-2 = 8
(will fail due to bug)
This shall assert that 8/2=5
(will fail, as this is incorrect!)
// @Test – deactivated, as it will cause an error (division by 0); more in T16
public void divideByZero() {
Dividing by 0 must lead to an
calculator.divide(0);
expected error, else test fails
}
Introduction to Computer Science I: T12
77
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Calculator Test Class (Part IV)
// @Ignore has a String parameter which displays a message
@Test
@Ignore("not ready yet")
Ignore testing multiply, as the
public void multiply() {
implementation is not ready yet.
calculator.add(10);
calculator.multiply(10);
assertEquals(calculator.getResult(), 100);
}
}
• Copy the classes from the course web page
• Make sure that JUnit 4.4 is installed and added to your project
as an “External JAR”
• Select the class CalculatorTest and choose Run As JUnit Test
• The output is shown on the next slide
Introduction to Computer Science I: T12
78
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
JUnit in Eclipse: Assert Methods etc.
Introduction to Computer Science I: T12
79
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
JUnit in Eclipse: Run as test case
Introduction to Computer Science I: T12
80
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Error Output from JUnit
Brief test results
Log of tests run
10-2=8 failed
Introduction to Computer Science I: T12
81
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
More Advanced Tests
• We have not used the divideByZero test method
– If we do so, we get an (expected) error message!
– How we can test for the presence of expected errors will be
covered together with error treatment in T16.
• We have not tested the squareRoot method so far
– Would not be a good idea, since this loops indefinitely!
• We also should do a general set-up once
– Create and switch on the calculator before tests are run
– Switch it off once all tests are finished and set to null
• The following code takes a closer look achieving this
– Slightly simplified from the code on the web page
Introduction to Computer Science I: T12
82
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Advanced Testing: General Set-Up
package junit4demo;
import calc.Calculator;
Make external class visible (T15)
import junit.framework.JUnit4TestAdapter;
import org.junit.AfterClass;
Run once when all tests are finished
import static org.junit.Assert.assertEquals;
import org.junit.Before;
Run before each test
import org.junit.BeforeClass;
import org.junit.Test;
Run once before any test is started
/**
* This test uses advanced fixture and timeout
*/
public class AdvancedTest {
private static Calculator calculator;
// Used for backward compatibility (IDEs, Ant and JUnit 3 text runner)
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(AdvancedTest.class);
}
Introduction to Computer Science I: T12
83
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Test Initialization and Finishing
Run once before testing starts:
@BeforeClass
create and switch on the calculator
// must be public and static
public static void switchOnCalculator() {
System.out.println("\tSwitch on calculator");
calculator = new Calculator();
calculator.switchOn();
}
Run once after all tests are completed:
switch off calculator and reset attribute
to null
@AfterClass
// must be public
public static void switchOffCalculator() {
System.out.println("\tSwitch off calculator");
calculator.switchOff();
calculator = null;
}
Introduction to Computer Science I: T12
84
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Tests with Timeout
//==================================
//=
Test cases
//==================================
@Test(timeout = 1000)
public void squareRoot() {
calculator.squareRoot(2);
}
@Test
public void square2() {
calculator.square(2);
assertEquals(4, calculator.getResult());
}
// two more tests skipped
}
If not done within 1000ms, this test
will fail (needed for indefinite loop!)
Tests for the squares of 4 & 5
Introduction to Computer Science I: T12
85
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Test Output with Timeout
Test for squareRoot failed due to time out
Introduction to Computer Science I: T12
86
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
More on JUnit...
• JUnit can do far more than shown here
• However, this is beyond the scope of this lecture
• Please take a look at the documentation
– Included JavaDoc for JUnit
– Good Reference (and base for these slides):
Antonio Goncalves, Get Acquainted with the New Advanced Features
of JUnit 4
http://www.devx.com/Java/Article/31983/0/page/1
Introduction to Computer Science I: T12
87