Top Banner
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only 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
87

Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Mar 28, 2015

Download

Documents

Paris Timpson
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Telecooperation/RBG

Technische Universität Darmstadt

Copyrighted material; for TUD student use only

Introduction to Computer Science ITopic 11: Introduction to OOP with Java:

Classes and Object

Prof. Dr. Max MühlhäuserDr. Guido Rößling

Page 2: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

• 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

Lecture Outline

2

Page 3: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

3

Page 4: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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 4

Page 5: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Object-Oriented Programming (OOP)

5

ownedBy

Rich

owned

By

manages

man

ages

Smith

Miller

employeemanager

ImportantThe world of Fine&Expensive

Page 6: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Object-Oriented Programming (OOP)

6

Object

Person House

Employee Client One-familyhouse

Multifamily-residence

ManagerHouse-

Managermanages

0..2

owns *

responsible for

2..10

Concepts & Categorization

Ur_Object TypeThe world of real estate companies

Page 7: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Object-Oriented Programming (OOP)

7

Object

Person House

Employee Client One-familyhouse

Multifamily-residence

ManagerHouse-

Manager

owns *

responsible for

2..10

manages

0..2

The world of rental companies

A concreteinstantiation

Page 8: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Classes and Constructor Operations

8

• 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

Page 9: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Classes in Java

• 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

9

<ClassDefinition> = class Class-Name [extends SuperClassName] <ClassDefinitionBlock>

<ClassDefinitionBlock> = { <MemberDefinition> ... <MemberDefinition> }<MemberDefinition> = <FieldDeclaration>

| <OperationDefinitons>| <ConstructorDefinitions>

Page 10: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

10

class Counter { int currentVal; ...}

type

nameRemember: 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 { int currentVal = 10; ...} value

Page 11: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

11

class Counter { int currentVal; ... Counter(int initVal) { currentVal = initVal; } ...}

formal parameter of the constructor

attributes are initialized with values of the actual parameters of the constructor call

(define (make-counter initVal) (local ( (define currentVal initVal) ...)

Page 12: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

12

... (define c1 (make-counter 3)) (define c2 (make-counter 6)) ...

... Counter c1 = new Counter(3); Counter c2 = new Counter(6); ...

keyword for the creation of object

instances

Page 13: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

The Java Class Counter

13

Visible outside the

body of Counter

JavaDoc comment. Abbreviated due to lack of space on slide.

class Counter { int currentVal;

public Counter(int initVal) { currentVal = initVal; }

/** * 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; }

/** * @return the current value of the counter */ public int getCurrentVal() { return currentVal; }}

Page 14: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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)

14

Page 15: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Class Interfaces in Scheme and Java• Scheme’s service managers (dispatchers) are

interface functions:– map symbols to functions of different types

• 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…

15

An address-book is an interface:'add :: symbol number -> void 'search :: symbol -> number

Page 16: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Encapsulation in Java (Information Hiding)

16

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...

class Counter { int currentVal; ...}

Page 17: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Encapsulation (Information Hiding)

17

• 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

Page 18: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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”

18

Page 19: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Classes as a two-fold abstraction

19

• … 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

Page 20: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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 20

Page 21: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Characteristics of an Object

21

Page 22: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Performing Computations• 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

22

public class CounterConsumer {Counter c1 = new Counter(3);Counter c2 = new Counter(6);

public void doSomethingWithCounters() {c1.inc();c1.inc();c1.dec();System.out.println(c1.getCurrentVal());

c2.inc();c2.dec();System.out.println(c2.getCurrentVal());

}}

(begin (inc c1) (inc c1) (dec c1))

(begin (inc c2) (dec c2))

(getCurrentVal c2)

(getCurrentVal c1)

Page 23: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

23

Page 24: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

javac CounterTest.java

java CounterTest

Remember: How Everything Begins...

There is a special method called main which is called automatically when a Java program is run…

24

public class CounterTest { // ...

public static void main(String[] args) { CounterConsumer cc = new CounterConsumer(); cc.doSomething (); } // ...} CounterTest.java

Java Compiler

Java Bytecode

Interpreter

Page 25: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

25

Page 26: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Interpreter

26

• 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 outExp4. Repeat steps 1 to 3 for the next expression

in the input program following inpExp

Page 27: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Compiler• A compiler is a program that translates programs

from a source language A to a target language B

27

Program in language A

Program in language B

compiler

target program P2

source program P1

A source language B target language

execu

tion

• 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

Page 28: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Compiler

28

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."

Page 29: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Stages of Compilation

Source code gets chopped into a sequence of terminals(tokens, words)

29

Lexical Analysis

Syntactic Analysis

Semantic Analysis

Code Generation

Tests if the source code conforms to the syntactical rules of the source language. Organizes terminal symbols in valid sentences.

Tests if all names used in the source are declared and then used according to their types.

Target program is generated

Page 30: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Traditional Compilation

30

source program in language A

Compiler for language A andprocessor X

Compiler forlanguage A andprocessor Y

Compiler for language A andprocessor Z

Executable program(binary code) forprocessor X

Executable program(binary code) forprocessor Z

Executable program(binary code) forprocessor Y

Linux

Windows

MacOS

PascalPascal

SmalltalkSmalltalk

JavaJava

PrologProlog

C++C++

N Languages M PlatformsN*M Compilers

Page 31: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Advantages and Disadvantages of Interpreters

31

- 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

Page 32: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Advantages and Disadvantages of Traditional Compilation

32

• 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.“

Page 33: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Drawbacks of Traditional Compilation

33

• 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

Page 34: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

assembler-like 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 assembler-like intermediate language

• A VM hides the specific properties of a certain processor type adds a new abstraction layer on top of hardware!

34

Page 35: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Virtual Machines (VM)

35

Linux

Windows

MacOS

PascalPascal

SmalltalkSmalltalk

JavaJava

PrologProlog

C++C++

N LanguagesM PlatformsN + M Compilers

VirtualMachineVirtual

Machine

Page 36: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Advantages and Disadvantages of VMs

36

• 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

byte-code to an executable program for a specific processor type / OS• When the code is loaded or the first time

the instructions are executed

Page 37: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Java Compilation und Runtime Environment

37

Page 38: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

38

Page 39: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

39

Page 40: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

40

class Cl1 {...}class Cl2 {...}class Cl3 {...}

Java C

om

pile

r

Cl1.class

Cl2.class

Cl3.class

SomeFile.java

Page 41: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

• 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

Lecture Outline

41

Page 42: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

42

Page 43: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Variable Visibility within a Java Class

43

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 …

} }

Page 44: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

• 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

Lecture Outline

44

Page 45: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

45

Page 46: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Package Hierarchies

• Packages are organized hierarchically A package may contain other packages Which in turn can contain packages, etc.

• “Dot” notation for package names

46

package.subpackage.subsubpackage.Class

• The preamble of a .java file determines with which package the following classes are associated

Page 47: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Package Naming Conventions

47

• 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

Page 48: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Package Declaration

• The same package name may be used in several files– One package may contain several filesFaster (re-)compilationsupports 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

48

Page 49: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

49

Page 50: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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>;

50

Page 51: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Using Packages

• Using full qualification

java.util.Random numberGenerator

= new java.util.Random();

• Using import

import java.util.Random;

...

Random numberGenerator = new Random();

51

Page 52: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Package Import• Importing classes with the same name yields a

name conflictimport java.awt.*; // contains class Listimport 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.

52

Page 53: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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.

53

Page 54: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Package Naming

• 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

54

Package names and directory structures

Page 55: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Binding Packages

• 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 UNIXCLASSPATH=.:/home/joe/classes:/usr/classes.zip

55

separates directoriescurrent directory

Packages and the "CLASSPATH"

Page 56: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Binding Packages

• 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

56

Packages and the "CLASSPATH"

Page 57: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

• 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

Lecture Outline

57

Page 58: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Testing with JUnit and Eclipse

58

Poor kid, we should have told him to test, then code when he started

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

Page 59: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

59

We use a testing framework, here JUnit:- for automated unit tests

Page 60: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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, …

60

Page 61: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

“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

61

Page 62: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

62

Page 63: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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:

63

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface UseCase { public int id(); public String description() default "no description";}

Page 64: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Annotations: Example

• Using previous annotations to define use cases

64

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... }}

Page 65: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

65

Page 66: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Test stages

66

Client wishes

Design

Code

Acceptance Tests

System tests

Integration tests

Unit tests

X Y

A happens before BA B X finds faults in Y

Requirements

Development stages with corresponding Tests

Page 67: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

67

Page 68: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Testing & Development Methodologies

68

time pressure

less tests

more errors

more time

pressure

An unwanted vicious circle…

Page 69: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Testing & Development Methodologies:“Agile” Methodologies

69

test alittle

code a little

• Development & testing as interleaved activities

• Test case creation before code is written• Tool support required

Page 70: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

70

Page 71: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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!

71

Page 72: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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; }

72

Page 73: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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; }}

73

Page 74: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

74

Page 75: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

The CalculatorTest Class (Part I)package junit4demo;

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;

/** * 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() { return new JUnit4TestAdapter(CalculatorTest.class); }

75

Choose any package name here

This is our calculator code Several needed imports for

JUnit

Import only this static method from class

Assert

Needed for older environments

Page 76: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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); }

76

@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.

Page 77: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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); }

// @Test – deactivated, as it will cause an error (division by 0); more in T16 public void divideByZero() { calculator.divide(0); }

77

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!)

Dividing by 0 must lead to an expected error, else test fails

Page 78: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

The Calculator Test Class (Part IV) // @Ignore has a String parameter which displays a message @Test @Ignore("not ready yet") public void multiply() { calculator.add(10); calculator.multiply(10); assertEquals(calculator.getResult(), 100); }}

78

Ignore testing multiply, as the implementation is not ready yet.

• 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

Page 79: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

JUnit in Eclipse: Assert Methods etc.

79

Page 80: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

JUnit in Eclipse: Run as test case

80

Page 81: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Error Output from JUnit

81

Log of tests run

Brief test results

10-2=8 failed

Page 82: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

82

Page 83: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Advanced Testing: General Set-Uppackage junit4demo;

import calc.Calculator;import junit.framework.JUnit4TestAdapter;import org.junit.AfterClass;import static org.junit.Assert.assertEquals;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;

/** * 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); }

83

Run once when all tests are finished

Run before each test

Run once before any test is started

Make external class visible (T15)

Page 84: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Test Initialization and Finishing @BeforeClass // must be public and static public static void switchOnCalculator() { System.out.println("\tSwitch on calculator"); calculator = new Calculator(); calculator.switchOn(); }

@AfterClass // must be public public static void switchOffCalculator() { System.out.println("\tSwitch off calculator"); calculator.switchOff(); calculator = null; }

84

Run once before testing starts: create and switch on the calculator

Run once after all tests are completed: switch off calculator and reset attribute to null

Page 85: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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}

85

If not done within 1000ms, this test will fail (needed for indefinite loop!)

Tests for the squares of 4 & 5

Page 86: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

Test Output with Timeout

86

Test for squareRoot failed due to time out

Page 87: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: Introduction.

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation

©

Introduction to Computer Science I: T12

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

87