2 Lecture OutlineObject-oriented design in a nutshell; classes and objects in JavaInterpreters, compilers, virtual machines; Java compile and runtime environmentVisibility of variables in JavaPackagesIntroduction to testing Java classes with Eclipse and JUnit

3 Object-oriented programming (OOP)OOP: one of the existing programming paradigmsOther paradigms: functional programming, logic programmingOOP models “the world” as a set of cooperating objects, where:Each object is responsible for a well-defined part of the overall computationEncapsulates the definition of the data needed for this part of the computation and of operations that process this dataCan use services of other known objects to perform the computationEach object is an instance of a classClasses are organized in an inheritance hierarchyClass hierarchies correspond to concept hierarchies in the application domain to be modeled

4 Object-Oriented Programming (OOP)Initial example: writing software for the real estate company Fine&Expensive, which manages and rents exclusive housesObjects will represent houses, employees, and clientsFor 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 commonOne-family house, multifamily residence

8 Classes and Constructor OperationsIn general, a class describes the common aspects of a group of objects (instances) that sharethe same set of properties (attributes)the same behavior (operations)Data (Variables)MethodsBlueprint (template) for objects; describes their structure and services

10 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 valueThe name is mostly written in lower caseAttribute values change during program executionRemember: int is a primitive type in Java.It represents the class of natural numbers between-2,147,483,648 and 2,147,483,647class Counter {int currentVal;...}nametypeclass Counter {int currentVal = 10;...}(define (make-counter)(local ((define currentVal 10)...)value

12 Constructor OperationsInitialization instructions are defined in a class once and used multiple timesCreation of multiple counter instances of the same type with differently initialized attributeskeyword 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))

14 Classes in Scheme and JavaScheme classes are modeled by constructor functions (make-XXX)Play at the same time the role of Java constructorsReturn dispatcher functions:Combine and hide all service functions  the only service visible from the outside is the dispatcherJava provides a special form for class definitionsClasses are no first-class values  cannot be passed as parameters or returned from functionsA class can have multiple initialization instructionsThe dispatch mechanism is an implicit language featurethe dispatcher is part of the Java semantics and does not need to be programmed (more on dispatching operation calls in the next lecture)

15 Class Interfaces in Scheme and JavaScheme’s service managers (dispatchers) are interface functions:map symbols to functions of different typesThe interface of a Java class results from the set of operations that are declared public…All non-public operations are invisible from the outsideFor now, we say that they can only be called from (public) operations of the same classNot quite true; will reconsider laterThe concept of an interface as a function that binds symbols to operations with a different contracts remains valid…An address-book is an interface:'add :: symbol number -> void'search :: symbol -> number

16 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

17 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 applicationNo need to understand the hidden details in order to use some moduleReduces coupling between modulesCan change hidden implementation details without invalidating clientsModule interface as contractWe have already seen this design ideadata abstraction: hide representation of data typeMake-functions hide local definitions of objects

18 Encapsulation and AbstractionIdea: 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 compositionEncapsulation is a mechanism to hide informationTerm sometimes used in a more general senseAs a synonym for information hidingTerm sometimes used in a more specific (OO) senseMeaning “data and operations together”

19 Classes as a two-fold abstraction… describe only those attributes and services of real objects that are relevant for the software to modelA class definition ignores irrelevant differences between all possible elements (objects) of a classThe class Counter ignores possible differences in the current value of the individual counters of this type

20 Classes & ObjectsClasses in Java are static descriptions ("on paper", respectively: "in the file")  "blueprints"Objects are run-time entities of a program  valuesdynamic (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 stateCan be accessed by means of a nameEach object belongs to a class and knows its classA class does not (usually) know its objects

22 Performing ComputationsAny computation in an OO program is the result of invoking an operation on a previously created objectNote the dot-notation for operation invocationpublic class CounterConsumer {Counter c1 = new Counter(3);Counter c2 = new Counter(6);public void doSomethingWithCounters() {c1.inc();c1.dec();System.out.println(c1.getCurrentVal());c2.inc();c2.dec();System.out.println(c2.getCurrentVal());}(begin(inc c1)(dec c1))(getCurrentVal c1)(begin(inc c2)(dec c2))(getCurrentVal c2)

23 Performing ComputationsThe task is divided into service instructionsFormulated as messages (operation invocations) to objectsEach message contains:Name of the receiver object: c1 in the exampleName of the service (operation) that the receiver shall executeinc(), dec(), ...The operation must be contained in the receiver's interfaceOnly one message is sent at any point in timeIf there are multiple objects, they can send messages to each otherDelegate substasks to known objects

24 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.javaJava Compilerjavac CounterTest.javajava CounterTestJava Bytecode Interpreter

25 Lecture OutlineObject-oriented design in a nutshell; classes and objects in JavaInterpreters, compilers, virtual machines; Java compile and runtime environmentVisibility of variables in JavaPackagesIntroduction to testing Java classes with Eclipse and JUnit

26 InterpreterWe have seen that an interpreter is a program that directly executes another program written in a certain programming languageOperation mode of interpreters. Let inpExp be the next expression to be executed in the input program:Perform a syntactic analysis of inpExpMap inpExp to an expression (sequence) outExp in the machine language, or the language of the interpreter itself (meta-circular interpreter)Execute outExpRepeat steps 1 to 3 for the next expression in the input program following inpExp

27 Compiler Program in language A Program in language B compilerA compiler is a program that translates programs from a source language A to a target language BProgram inlanguage AProgram inlanguage BcompilerexecutionA  source languageB  target languagesource program P1target program P2Semantic correctness:Every program P1 in A corresponds to exactly one program P2 in BThe destination program P2 must have the same meaning (semantics) as P1

28 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."Pioneer Computer Scientist:Perhaps her best-knowncontribution to computing wasthe invention of the compiler,the intermediate program thattranslates English languageinstructions into the language ofthe target computer.

29 Stages of CompilationSource code gets chopped into a sequence of terminals (tokens, words)Lexical AnalysisTests if the source code conforms to the syntactical rules of the source language. Organizes terminal symbols in valid sentences.Syntactic AnalysisTests if all names used in the source are declared and then used according to their types.Semantic AnalysisCode GenerationTarget program is generated

31 Advantages and Disadvantages of InterpretersAdvantage: Good support of the testing/prototyping stage of the program  fast prototypingChanged expressions / declarations of the source code directly executableRetranslation of the program not necessaryDisadvantage: executing takes longerIf expressions are used k times in the source code (e.g., in loops), they are analysed and dispatched k timesFor each access of the same variable in different locations in the program, the respective address must be determined over and over again

32 Advantages and Disadvantages of Traditional CompilationAdvantage: Optimal utilization of the processor propertiesVery fast execution of the compiled programsDisadvantage: 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.“

33 Drawbacks of Traditional CompilationThe compiled program runs only on one processor type or operating systemIt must be compiled with a different compiler for each processor type or operating systemWindows on PC != Linux on PCProgramming languages are often defined in a platform dependent waySpecific properties of the machine affect the design of the compilerE.g., the size of registers or memory cells which in turn affect the maximal length of the numbers that can be manipulatedConsequence: There are often different dialects of a programming language

34 Virtual Machines (VM)A virtual machine is a program (software) that simulates a hardware processorPrograms in a higher programming language (e.g., Java) are compiled into the intermediate languageThe simulated hardware processor has a set of assembler-like instructions that it understands and a set of software registersThe instructions of the intermediate language are often called byte codeThe VM serves as an interpreter for this assembler-like intermediate languageA VM hides the specific properties of a certain processor type  adds a new abstraction layer on top of hardware!

36 Advantages and Disadvantages of VMsAdvantages: compiled programs run on all processor types or OS for which there exists a VMOnly one compiler is needed for all processor types or operating systemsThe higher-level language becomes independent of different hardware platforms or OSOf course, you need one VM per processor and OSDisadvantages: byte-code programs are slower than machine programsSolution: just-in-time-compiler compiles byte-code to an executable program for a specific processor type / OSWhen the code is loaded or the first time the instructions are executed

38 Structure of a Java ProgramA Java program consists of an arbitrary number of classes, at least one of which must contain the main operationResponsibility of the main operation:Object creation  the construction of an initial minimal set of objectsCalling the first operationIn general, it should not contain further control flow of the Java programThe real control flow is encapsulated within the implementation of the operations of cooperating objectsRemember that computations are organized by multiple cooperating objects, and each object covers only a small sub-taskThe main operation will be started and executed by means of the Java interpreterargs ist eine Tabelle mit Zeichenketten und wird benutzt um dem Programm beim Start Parameter zu übergebenEingabeparameter stehen zunächst nur als Zeichenketten zur VerfügungMöchte man eine Zahl übergeben, so muss die entsprechende Zeichenkette (programmintern) in eine Zahl (z.B. vom Typ int) konvertiert werden  mehr dazu späterStatt args kann ein beliebiger Name benutzt werden, die Verwendung von args ist aber üblich

39 Java Runtime EnvironmentJava Interpreter: program for executing Java byte codes on a particular machineJust-In-Time Compiler (JIT-Compiler) :After being loaded, a class can (optimally) be directly translated into the machine code of the particular machineIf the Java installation at hand does not have a JIT compiler, the byte code will be directly executed by the Java interpreterRuntime System: provides important resources to Java program  irrelevant to this courseByte code-Verifier: verifies that the loaded byte codes satisfy the JVM specificationClasses can be loaded from the Internet or from the local file system at the runtime of a Java applicationPart of the security provisions are performed by the verifier

40 Java Compilation (Repeated)Java compilerInput: Java source file, SomeFile.java, that contains one or more class definitionsSuch a file is called compilation unitOutput: for each class Cl in SomeFile.java, the compiler will generate exactly one file Cl.class that contains the bytecode for the class ClSomeFile.javaCl1.classclass Cl1 {...}class Cl2 {...}class Cl3 {...}Cl2.classJava CompilerCl3.class

41 Lecture OutlineObject-oriented design in a nutshell; classes and objects in JavaInterpreters, compilers, virtual machines; Java compile and runtime environmentVisibility of variables in JavaPackagesIntroduction to testing Java classes with Eclipse and JUnit

42 Variable Visibility within a Java ClassAs in Scheme, a name may be used multiple times for different purposes, e.g., as an instance variable, a parameter, a local variableSimilar to Scheme, Java employs lexical scoping: inner declarations have precedence over outer declarationsOuter declarations are not directly accessible anymoreUsing this.<attribute name> one may still access instance variablesLocal variables and parameters may not be re-declaredA re-declaration does not affect the existence of the outer variableInvisibility does not imply non-existence; outside the re-declaring block, the outer variable is visible again

44 Lecture OutlineObject-oriented design in a nutshell; classes and objects in JavaInterpreters, compilers, virtual machines; Java compile and runtime environmentVisibility of variables in JavaPackagesIntroduction to testing Java classes with Eclipse and JUnit

45 PackagesPackages bundle up classes which belong together with respect to an area of responsibilityHelp to avoid name conflictsClass names have to be unique (but only within a package)Two or more classes may use the same (non-public) class name, e.g., ListHide classes which only serve an internal purpose and should not be visible from outside

46 Package Hierarchies Packages are organized hierarchicallyA package may contain other packagesWhich in turn can contain packages, etc.“Dot” notation for package namespackage.subpackage.subsubpackage.ClassThe preamble of a .java file determines with which package the following classes are associated

48 Package Declaration The same package name may be used in several filesOne package may contain several filesFaster (re-)compilationsupports workload distribution in larger projectsThe 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

50 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 nameIf "*" (wild card) is used, all classes contained in the package may be accessedIf you only want to import class methods (static), use this notation:import static <Package-Name>.<Class-Name>.<Methode>;

51 Using Packages Using full qualificationjava.util.Random numberGenerator= new java.util.Random();Using importimport java.util.Random;...Random numberGenerator = new Random();

55 Binding Packages Packages and the "CLASSPATH"A package name is interpreted as a relative pathThe environment variable CLASSPATH contains all directories which are to be searched for classes or packagesAlternatively, a CLASSPATH may also contain ZIP- or JAR-archives, containing classesExample for UNIXCLASSPATH=.:/home/joe/classes:/usr/classes.zipcurrent directoryseparates directories

56 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 rightIt is possible that one package name exists in two or more existing directoriesNot a good idea, as the selection of a package then depends on the order of the paths in CLASSPATH

57 Lecture OutlineObject-oriented design in a nutshell; classes and objects in JavaInterpreters, compilers, virtual machines; Java compile and runtime environmentVisibility of variables in JavaPackagesIntroduction to testing Java classes with Eclipse and JUnit

58 Testing with JUnit and EclipseTest-first programming  Our design recipes require that we write tests before we start codingJUnit is a program (framework) that automates parts of the process of writing and running testsJUnit is already integrated into EclipsePoor kid, we should have told him to test, then code when he started

59 Motivation: JUnitSimilarly to our test cases for Scheme, we also want to be able to test our Java programsWe 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 programWhenever we want to know if certain test cases still work correctWe use a testing framework, here JUnit:- for automated unit tests

60 Annotations Before we look at JUnit, let us take a look at annotationsThe latest version of JUnit is implemented with annotationsAnnotations give metadata about codeJava 1.5+ defines seven annotationsIt is possible to add user-defined annotationsThere are three “real” annotations……and four “meta” annotationsAnnotations are marked in codeForAnnotations refer to the following elementElement = line of code, method, …

61 “Real” Annotations @Override @Deprecated @SuppressWarningsIndicates that a method overrides a method in the base classCan be used to check for typos or errors in method signature@DeprecatedProduces a compiler warning if the element is used@SuppressWarningsTurn off compiler warnings for the following element

65 Annotations and JUnitThe latest version of JUnit is based on annotationsTest cases are marked withEarlier versions relied on specific naming conventions for test classes; not needed anymoreWe will come back to JUnit in a moment…But first, a few more words about testing

67 Test stages In different stages, different test strategies are usefulUnit Test: Test of code components, e.g. code of a method or a class  structural testingIntegration test: Test of the integration of multiple code components  structural testingSystem test: Test of the whole system against the specification  functional testingAcceptance test: Test of the whole system with real data from the client

70 Testing Testing is a necessity in real lifeThe earlier faults are found, the better (and cheaper)Development usually is an iterative process with feedback loopsIf possible, do not only test for quality, but build for qualitySystematic Procedures  Software Engineering

71 Testing with Junit 4.4In the following, we will test a small calculatorThe implementation of this class is rather easyIt will only work for int valuesIt is very simple and inefficientIt also has a couple of bugsWe will see how JUnit can help us track those bugs!

74 How Do We Test A Calculator?We want to test each operation separatelyAddSubstractDivideMultiplySquare Root – deferred for now (indefinite loop!)We write one test method per testThe methods go into a separate class CalculatorTestTests are annotated before the “public”We need to initialize the calculator before each testNeed to send “clear()” to ensure the value is 0Otherwise, we get incorrect follow-up errors

76 The Calculator Test Class (Part II)@Before // must be public not protected like the setup public void clearCalculator() { calculator.clear(); } //================================== // Test public void add() { 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.

77 The Calculator Test Class (Part III)public void subtract() {calculator.add(10);calculator.substract(2);assertEquals(calculator.getResult(), 8);}public void divide() {calculator.add(8);calculator.divide(2);assertEquals(calculator.getResult(), 5);– deactivated, as it will cause an error (division by 0); more in T16public void divideByZero() {calculator.divide(0);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

78 The Calculator Test Class (Part IV)has a String parameter which displays ready yet") public void multiply() { calculator.add(10); calculator.multiply(10); assertEquals(calculator.getResult(), 100); }Ignore testing multiply, as the implementation is not ready yet.Copy the classes from the course web pageMake 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 TestThe output is shown on the next slide

82 More Advanced Tests We have not used the divideByZero test methodIf 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 farWould not be a good idea, since this loops indefinitely!We also should do a general set-up onceCreate and switch on the calculator before tests are runSwitch it off once all tests are finished and set to nullThe following code takes a closer look achieving thisSlightly simplified from the code on the web page

84 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(); // must be public public static void switchOffCalculator() { System.out.println("\tSwitch off calculator"); calculator.switchOff(); calculator = null;Run once before testing starts: create and switch on the calculatorRun once after all tests are completed: switch off calculator and reset attribute to null

87 More on JUnit... JUnit can do far more than shown hereHowever, this is beyond the scope of this lecturePlease take a look at the documentationIncluded JavaDoc for JUnitGood Reference (and base for these slides):Antonio Goncalves, Get Acquainted with the New Advanced Features of JUnit 4

About project

Feedback

To ensure the functioning of the site, we use cookies. We share information about your activities on the site with our partners and Google partners: social networks and companies engaged in advertising and web analytics. For more information, see the Privacy Policy and Google Privacy &amp Terms.
Your consent to our cookies if you continue to use this website.