Innocent-human.pdf

  • Uploaded by: sufyan maher
  • 0
  • 0
  • December 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Innocent-human.pdf as PDF for free.

More details

  • Words: 61,217
  • Pages: 174


POUL KLAUSEN

JAVA 3: OBJECTORIENTED PROGRAMMING SOFTWARE DEVELOPMENT

2

Java 3: Object-oriented programming: Software Development 1st edition © 2017 Poul Klausen & bookboon.com ISBN 978-87-403-1691-9 Peer review by Ove Thomsen, EA Dania

3

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Contents

CONTENTS Foreword

6

1 Introduction

8

2 Classes

15



Exercise 1

20

2.1

More classes

22



Exercise 2

34



Exercise 3

35



Problem 1

38

2.2 Methods

41

2.3 Objects

46

2.4 Visibility

48

2.5

Statical members

49

2.6

The CurrencyProgram

53



Problem 2

66

www.sylvania.com

We do not reinvent the wheel we reinvent light. Fascinating lighting offers an infinite spectrum of possibilities: Innovative technologies and new markets provide both opportunities and challenges. An environment in which your expertise is in high demand. Enjoy the supportive working atmosphere within our global group and benefit from international career paths. Implement sustainable ideas in close cooperation with other specialists and contribute to influencing our future. Come and join us in reinventing light every day.

Light is OSRAM

4

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Contents

3 Interfaces

69

3.1 Interfaces

70



Exercise 4

82

3.2

More students

83



Exercise 5

91

3.3 Factories

94



Exercise 6

97

4 Inheritance

98



Exercise 7

111



Problem 2

112

4.1

More about inheritance

118

5

The class Object

119

6

Typecast of objects

128

7

A last note about classes

130

7.1

Considerations about inheritance

130



Problem 3

134

7.2

The composite pattern

142

8

Final example

143

8.1 Analyse

144

8.2 Design

148

8.3 Programming

155



Appendix A

159



Comment the code

159



Debug the code

162



Unit test

164

5

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Foreword

FOREWORD This book is the third in a series of books on software development. The programming language is Java, and the language and its syntax and semantics fills obviously much, but the books have also largely focus on the process and how to develop good and robust applications. In the first book I have generally mentioned classes and interfaces, and although the book Java 2 also intesiv used classes and interfaces I have deferred the details to this book and also the next, that are dealing with object-oriented programming. It deals with how a running program consists of cooperating objects and how these objects are defined and created on the basis of the program’s classes. Object-oriented programming is the knowledge of how to find and write good classes to a program, classes which helps to ensure that the result is a robust program that is easy to maintain. The subject of this book is object-oriented programming and here primarily about classes and how classes are used as the basic building blocks for developing a program. The book assumes a basic knowledge of Java corresponding to the book Java 1 of this series, but since some of the examples and exercises are relating to programs with a graphical user interface it is also assumed knowledge of the book Java 2 and how to write less GUI programs. As the title says this series of books deals with software development, and the goal is to teach the reader how to develop applications in Java. It can be learned by reading about the subject and by studying complete sample programs, but most importantly by yourself to do it and write your own programs from scratch. Therefore, an important part of the books is exercises and problems, where the reader has to write programs that correspond to the substance being treated in the books. All books in the series is built around the same skeleton and will consist of text and examples and exercises and problems that are placed in the text where they naturally belongs. The difference between exercises and problems is that the exercises largely deals with repetitions of the substance that is presented in the text, and furthermore it is relatively accurately described what to do. Problems are in turn more loosely described, and are typically a little bigger and there is rarely any clear best solution. These are books to be read from start to finish, but the many code examples, including exercises and problems plays a central role, and it is important that the reader predict in detail studying the code to the many examples and also solves the exercises and problems or possibly just studying the recommended solutions. All books ends with one or two larger sample programs, which focus primarily is on process and an explanation of how the program is written. On the other hand appears the code only to a limited extent – if at all – and the reader should instead study the finished program code perhaps while testing the program. In addition to show the development of programs that are larger than the examples, which otherwise is presented, the aim of the concluding examples also is to show program examples from varying fields of application.

6

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Foreword

Most books also ends with an appendix dealing with a subject that would not be treated in the books. It may be issues on the installation of software or other topics in computer technology, which are not about software development, but where it is necessary to have an introductory knowledge. If the reader already is familiar with the subject, the current appendix can be skipped. The programming language is, as mentioned Java, and besides the books use the following products: -- NetBeans as IDE for application development -- MySQL to the extent there is a need for a database server (from the book Java 6 onwards) -- GlassFish as a web server and application server (from the book Java 11 onwards) It is products that are free of charge and free to install, and there is even talk about products, where the installation is progressing all by itself and without major efforts and challenges. In addition, there are on the web detailed installation instructions for all the three products. The products are available on Windows and Linux, and it therefore plays no special role if you use Linux or Windows. All sample programs are developed and tested on machines running Linux. In fact, it plays no major role, as both Java and other products work in exactly the same way whether the platform is one or the other. Some places will be in the books where you could see that the platform is Linux, and this applies primarily commands that concerning the file system. Otherwise it has no meaning to the reader that the programs are developed on a Linux machine, and they can immediately also run under Windows unless a program refers to the file system where it may be necessary to change the name of a file. Finally a little about what the books are not. It is not “how to write” or for that matter reference manuals in Java, but it is as the title says books on software development. It is my hope that the reader when reading the books and through the many examples can find inspiration for how to write good programs, but also can be used as a source collection with a number of examples of solutions to concrete everyday programming problems that you regularly face as a software developer.

7

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Introduction

1 INTRODUCTION Programs should deal with data, and data must be represented and stored, which happens in variables. A language like Java has a number of built-in types to variables (as explained in the book Java 1), but often you need to define your own data types that better reflects the task the program must solve. This is where the concept of a class comes in. A class is something that define a concept or thing within the problem area, and that can be said a lot about what a classes is, and what is not, but technically a class is a type. It’s a bit more than just a type, as a class partly defines how data should be represented, but also what we can do with the data of that type. A class defines both how the type will be represented, and what operations you can perform on variables of that type. Classes are also generally been described in the book Java 1, but in this book I will start or continue with a more detailed discussion of Java’s class concept. When wee create variables whose type is a class, wee talk about objects, so that a variable of a class type is called an object, but really there is no great difference between a variable and an object, and there is well along the road no reason to distinguish between the two. But dig a little further down, there is a reason that has to do with how variables and objects are allocated in the machine’s memory. Variables whose type is int, double, boolean, char, etc., are called simple variables or primitive types. To a running program is allocated a so-called stack that is a memory area used by the application among other to store variables. The stack is highly efficient, so that it is very fast for the program to continuously create and remove variables as needed. This is called a stack, because one can think of the stack as a data structure illustrated as follows:

8

JAVA JAVA3:3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA OBJECT-ORIENTED PROGRAMMING

Introduction IntroduCtIon IntroduCtIon

When Whenthe theprogram programcreates createsa aanew newvariable, variable,itit ithappens happensatat atthe thetop topofof ofthe thestack stack–– –where wherethe the When the program creates new variable, happens the top the stack where the arrow arrowisis ispointing, pointing,and andifif ifa aavariable variablemust mustbebe beremoved, removed,itit itisis isthe theone onethat thatlies liesatat atthe thetop topofof of arrow pointing, and variable must removed, the one that lies the top the thestack. stack.Variables Variablesofof ofsimple simpledata datatypes typeshave havethe theproperty propertythat thatthey theyalways alwaystake takeup upthe the the stack. Variables simple data types have the property that they always take up the same. same.As Asan anexample examplefills fillsan anint intthe thesame same(4(4 (4bytes), bytes),no nomatter matterwhat whatvalue valueitit ithas. has.Therefore Therefore same. As an example fills an int the same bytes), no matter what value has. Therefore for forthe thekind kindofof ofvariables variablesstored storeddirectly directlyon onthe thestack stackthe thecompiler compilerknows knowshow howmuch muchspace space for the kind variables stored directly on the stack the compiler knows how much space they theyuse. use.Thus, Thus,ifif ifone oneasas asan anexample exampleinin ina aamethod methodwrites writes they use. Thus, one an example method writes int a a = = 23; 23; int

then thenthere therewill willbebe becreated createda aavariable variableon onthe thestack stackofof oftype typeint intand andwith withthe thespace spaceasas asan anint int then there will created variable on the stack type int and with the space an int requires requires(4(4 (4bytes), bytes),and andthe thevalue valueisis isstored storedthere. there.Variables Variablesthat thatinin inthis thisway wayare arestored storeddirectly directly requires bytes), and the value stored there. Variables that this way are stored directly on onthe thestack, stack,are arealso alsocalled calledvalue valuetypes, types,and andthe thesimple simpleoror orprimitive primitivetypes types–– –except exceptString String–– – on the stack, are also called value types, and the simple primitive types except String are areallall allvalue valuetypes. types. are value types. Things Thingsare aredifferent differentwith withthe thevariables variablesofof ofreference referencetypes typessuch suchasas asvariables, variables,that thathas hasa aaclass class Things are different with the variables reference types such variables, that has class type. type.They Theyhave havetoto tobebe becreated createdexplicitly explicitlywith withnew. new.If,If, If,for forexample exampleyou youhave havea aaclass classnamed named type. They have created explicitly with new. for example you have class named Cube, Cube,and andyou youwant wanttoto tocreate createsuch suchan anobject, object,you youmust mustwrite write Cube, and you want create such an object, you must write Cube c c = = new new Cube(); Cube(); Cube

Itlooks lookslike, like,how howtoto tocreate createa aasimple simplevariable. variable.The Thevariable variableisis iscalled calledc.c. c.When Whennew newisis isexecuted, executed, looks like, how create simple variable. The variable called When new executed, ItIt whathappens happensisis isthat thaton onthe thea aaso-called so-calledheap heapisis iscreated createdan anobject objectofof ofthe thetype typeCube. Cube.One One what happens that on the so-called heap created an object the type Cube. One what canthink thinkofof ofthe theheap heapasas asa aamemory memorypool poolfrom fromwhich whichtoto toallocate allocatememory memoryasas asneeded. needed.On On can think the heap memory pool from which allocate memory needed. On can thestack stackisis iscreated createdan anusual usualvariable variableofof oftype typeCube, Cube,but butstored storedon onthe thestack stackisis isnot notthe thevalue value the stack created an usual variable type Cube, but stored on the stack not the value the ofa aaCube Cubeobject, object,but butrather rathera aareference referencetoto tothe theobject objecton onthe theheap. heap.All Allreferences referencestake takeup up Cube object, but rather reference the object on the heap. All references take up ofof thesame sameregardless regardlessofof ofthe thetype, type,and andthey theycan canthen thenbebe bestored storedon onthe thestack. stack.That Thatisis iswhy whyitit it the same regardless the type, and they can then stored on the stack. That why the iscalled calleda aareference referencetype. type.Where Whereexactly exactlyan anobject objectisis iscreated createdon onthe theheap heapisis isdetermined determinedby by called reference type. Where exactly an object created on the heap determined by isis so-calledheap heapmanager managerthat thatisis isa aaprogram programthat thatisis isconstantly constantlyrunning runningand andmanages managesthe the so-called heap manager that program that constantly running and manages the a aaso-called heap.ItIt Itisis isalso alsothe theheap heapmanager, manager,which whichautomatically automaticallyremoves removesan anobject objectwhen whenitit itisis isno no heap. also the heap manager, which automatically removes an object when no heap. longerneeded. needed. longer needed. longer

99 9

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Introduction IntroduCtIon

For For the the above above reasons, reasons, itit isis clear clear that that the the variables variables of of value value types types are are more more effective effective than than the the objects objects of of reference reference types. types. ItIt in in no no way way means means that that objects objects of of reference reference types types are are ineffective, ineffective, and and in in most most cases cases itit isis not not aa difference difference that that you you need need to to relate relate to, to, but but conversely conversely there there are are also also situations situations where where the the difference difference matters. matters. Thus, Thus, itit isis important important to to know know that that there there are are big big differences differences in in how how value value types types and and reference reference types types are are handled handled by by the the system, system, and and that that in in some some contexts contexts itit are are of of great great importance importance for for how how the the program program will will behave, behave, but but there’ll there’ll be be many many examples examples that that clarify clarify the the difference. difference. So So far, far, itit isis enough enough to to know know that that the the data data can can be be grouped grouped into into two two categories categories depending depending on on their their data data type, type, so so that that the the data data of of value value types types are are allocated allocated on on the the stack stack and and isis usually usually called called variables, variables, while while data data of of reference reference types types are are allocated allocated on on the the heap heap and and called called objects objects –– although although there there isis no no complete complete consistency consistency between between the the two two names. names. In In the the bokk bokk Java Java 1, 1, II defined defined the the following following class, class, which which represents represents aa usual usual cube: cube: public class Cube { private static Random rand = new Random(); private int eyes; public Cube() { roll(); } public int getEyes() { return eyes; } public void roll() { eyes = rand.nextInt(6) + 1; }

}

public String toString() { return "" + eyes; }

10 10

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA

Introduction IntroduCtIon IntroduCtIon

The Thevalue valueof ofthe theCube Cubeor orit’s it’sstate stateisisisrepresented representedby byan anint, int,while whileits itsproperties propertiesor orbehavior behavior The value of the Cube or it’s state represented by an int, while its properties or behavior isisrepresented by three methods. In a program, you can then create objects of type represented by by three three methods. methods. In In aa program, program, you you can can then then create create objects objects of of type typeCube Cube is represented Cube asasfollows: follows: as follows: Cube c1 c1 == new new Cube(); Cube(); Cube Cube c2 c2 == new new Cube(); Cube(); Cube

When Whenyou youcreate createan anobject objectof ofaaaclass, class,the theclass’s class’sinstance instancevariables variablesare arecreated, created,and andthen thenclass’s class’s When you create an object of class, the class’s instance variables are created, and then class’s constructor constructorisisisexecuted. executed.IfIfIfaaaclass classhas hasno noconstructor, constructor,there thereautomatically automaticallywill willbe becreated created constructor executed. class has no constructor, there automatically will be created aaadefault constructor – a constructor with no parameters. A constructor is characterized default constructor constructor –– aa constructor constructor with with no no parameters. parameters. AA constructor constructor isis characterized characterized default in that it is a method which has the same name as the class and do not have in that that itit isis aa method method which which has has the the same same name name asas the the class class and and do do not not have haveany anytype. type.AAA in any type. constructor constructorisisisaaamethod, method,but butitititcan cannot notbe becalled calledexplicitly explicitlyand andisisisperformed performedonly onlywhen whenan an constructor method, but can not be called explicitly and performed only when an object objectisisisinstantiated. instantiated.The Theclass classCube Cubehas hasaaaconstructor, constructor,that thatisisisaaadefault defaultconstructor. constructor. object instantiated. The class Cube has constructor, that default constructor. The Theobjects objectsare areas mentionednot notallocated allocatedon onthe thestack, stack,but butisisiscreated createdon onthe theheap. heap.c1 c1and and The objects are asasmentioned mentioned not allocated on the stack, but created on the heap. c1 and c2 c2are areusual usualvariables variableson onthe thestack, stack,but butdoes doesnot notinclude includethe theobjects objectsbut butinclude includeinstead instead c2 are usual variables on the stack, but does not include the objects but include instead references referencesto tothe thetwo twoobjects objectson onthe theheap. heap.It’s It’srare rareyou youas programmerneed needto tothink thinkabout about references to the two objects on the heap. It’s rare you asasaaaprogrammer programmer need to think about it, but in some situations it is important to know the difference between an object allocated it,but butin insome somesituations situationsititisisimportant importantto toknow knowthe thedifference differencebetween betweenan anobject objectallocated allocated it, on the stack and on the heap. The figure below illustrate how it looks in the machine’s on the the stack stack and and on on the the heap. heap. The The figure figure below below illustrate illustrate how how itit looks looks in in the the machine’s machine’s on memory memorywith withthe thetwo twovariables variableson onthe thestack stackthat thatrefer referto toobjects objectson onthe theheap: heap: memory with the two variables on the stack that refer to objects on the heap:

If, If,for forexample exampleyou youin inthe theprogram programwrites writes If, for example you in the program writes c1 == c2; c2; c1

11 1111

Deloitte & Touche LLP and affiliated entities.

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Introduction IntroduCtIon

itit means means that that there there no no longer longer is is aa reference reference to to the the object object as as c1 c1 before before referring referring to, to, but but there there are are instead instead two two references references to to the the object object as as c2 c2 refers refers to to (see (see the the figure figure below). below). If, If, you you then writes then writes c1.roll(); c2.roll();

it means that the same cube is rolled twice because both references refer to the same object. it means that the same cube is rolled twice because both references refer to the same object. When there are no longer are any references to an object, it also means that the object is When there are no longer are any references to an object, it also means that the object is automatically removed from heap by the heap manager and the memory that the object automatically removed from heap by the heap manager and the memory that the object used, will be deallocated. used, will be deallocated.

360° thinking

.

360° thinking

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers 12 12

Dis

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Introduction

A class is referred to as a type, but it is also a concept of design. The class defines objects state as instance variables, how objects are created, and which memory is allocated for the objects. Objects have at a given moment a value as the content of the instance variables, and an object’s value is referred to as its state. The class also defines in terms of its methods, what can be done with the object, and thus how to read and modify the object’s state. The methods define the object’s behavior. Every Java program consists of a family of classes that together defines how the program would operate and a running program will at a given time consist of a number of objects instantiated from the program’s classes, objects that work together to accomplish what the program now must do. The work to write a program is then to write the classes that the program should consist of. Which classes that is, are in turn, not very clearly, and the same program may typically be written in many ways made up of classes, which are quite different. The work to determine which classes a program should consist of and how these classes should look like in terms of variables and methods is called design. In principle, one can say that if a program does the job properly, it may be irrelevant, which classes it is composed of, but unsuitable classes means -- that it becomes difficult to understand the program and thus to find and fix errors -- that it in the future will be difficult to maintain and modify the program -- that it becomes difficult to reuse the program’s classes in other contexts Therefore, the design and choice of classes, is a very key issue in programming, and in that context wee are speaking of program quality (or lack thereof ). A class is more than just a type, but it is a definition or description of a concept from the program’s problem area. When you have to define which classes a program must consist of, you must therefore largely focus on classes as a tool to define important concepts more than the classes as a type in a programming language.

13

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Introduction

An object is characterized by four things: -----

a a a a

unique identifier that identifies a particular object from all other state that is the object’s current value behavior that tells what you can do with the object life cycle from when the object is created and to it again is deleted

An object is created from a class, and is that time assigned a reference that identifies the object. The class’s instance variables determine which variables to be created for the object, and the value of these variables is the state of the object. The class’s methods define what you can do with the object and thus the object’s behavior. The last point of concerning is the objects life cycle, which is explained later. To program in that way in which you see a program as composed of a number of cooperating objects, is called object-oriented programming. For many years wee have used object-oriented programming, and although it is primarily a question of design, it also requires that the current programming language supports the object-oriented thinking, and this is what makes Java an object oriented programming language. This book focuses on object-oriented programming, including both object-oriented design, and how it is supported in Java. There are many concepts that includes 1. objects life cycle 2. inheritance and polymorphism 3. generic types 4. collection classes all subjects that are discussed below, and in the next book. To explain these concepts I will consider classes as concerning students at an educational institution, as well as books in a library.

14

JAVA3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA

Classes Classes

2 CLASSES 2 CLASSES In the the book book Java Java 1, 1, II have have generally generally described described classes, classes, but but there there isis much much more more to to say, say, and and In classes are are the the whole whole fundamental fundamental concept concept in in object-oriented object-oriented programming. programming. This This book book isis classes therefore about about how how to to write write classes classes and and how, how, based based on on these these classes classes to to create create objects. objects. I’ll I’ll therefore start with with aa class class that that can can represent represent aa course course atat an an educational educational institution: institution: start package students; /** * Class which represents a subject associated with an education. * A subject consists in this context an id, which is an acronym that * identifies the subject and a name. */ public class Subject { private String id; // the subject id private String name; // the subject's name

We will turn your CV into an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? We will appreciate and reward both your enthusiasm and talent. Send us your CV. You will be surprised where it can take you.

15 15

Send us your CV on www.employerforlife.com

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

/** * Creates a new subject. A subject must have both an ID and a name, and is it * not the case, the constructor raises an exception. * @param id The subjects id * @param navn The subjects name * @throws Exception If the id or the name are illegal */ public Subject(String id, String name) throws Exception { if (!subjectOk(id, name)) throw new Exception("The subject must have both an ID and a name"); this.id = id; this.name = name; } /** * @return The subjects id */ public String getId() { return id; } /** * @return The subjects name */ public String getName() { return name; } /** * Changes the subject's name. The subject must have a name, and if the parameter * does not specify a name the method raises a exception. * @param navn The subjects name * @throws Exception If the name is null or blank */ public void setName(String name) throws Exception { if (!subjectOk(id, name)) throw new Exception("The subject must have a name"); this.name = name; } /** * @return The subjects name */

16 16

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

public String toString() { return name; }' /**

}

* Method tthat tests whether two strings can represent a subject. * @param id The subjects id * @param name The subjects name * @return true, if id and name represents a legal subject */ public static boolean subjectOk(String id, String name) { return id != null && id.length() > 0 && name != null && name.length() > 0; }

Compared saidsaid about classes in the Java 1Java there1 isthere not much to explain, Comparedtotowhat whatI have I have about classes in book the book is notnew much new to and the meaning of variables and methods are explained in the class as comments, but you must explain, and the meaning of variables and methods are explained in the class as comments, be the be following. butaware you of must aware of the following. Classes Classes are are defined defined by by the the reserved reserved word word class, class, and and aa class class has has aa name name as as here here is is Subject. Subject. In Java, it is recommended that you write the name of classes capitalized, but otherwise In Java, it is recommended that you write the name of classes capitalized, but otherwise applies applies the the same same rules rules for for classes classes names, names, that that makes makes the the names names of of variables. variables. A A class class can can have have aa visibility that may be public or private, but so far I will define all classes public. Visiblity visibility that may be public or private, but so far I will define all classes public. Visiblity says says something something about about who who may may use use the the class. class. Classes Classes consist consist of of variables variables and and methods, methods, and and there there is is in in principle principle no no upper upper limit limit for for any any of the two parts. Both variables and methods can have public and private visibility. If of the two parts. Both variables and methods can have public and private visibility. If aa member member (variable (variable or or method) method) is is public, public, it it can can be be referenced referenced from from methods methods in in all all other other classes, that have an object of the current class, and if it is private, it can only be referenced classes, that have an object of the current class, and if it is private, it can only be referenced by by methods methods in in the the class class itself. itself. Usually Usually you you define define variables variables as as private, private, while while the the methods methods to to be used by other classes, are defined public. Put a little different then a class defines with be used by other classes, are defined public. Put a little different then a class defines with public public methods, methods, what what can can be be done done with with objects objects of of the the class class and and thus thus the the objects objects behavior. behavior. In In this this case, case, the the class class has has two two variables, variables, both both of of which which are are of of the the type type String. String. Such Such variables variables are called instance variables, and each object of the class has its own copies of these variables are called instance variables, and each object of the class has its own copies of these variables whose whose values values are are the the object’s object’s state. state. The The type type String String is is also also aa class class type, type, and and the the two two variables variables are therefore reference types. They do not refer necessarily to anything and such variables are therefore reference types. They do not refer necessarily to anything and such variables has has the the value value null null (null (null reference), reference), which which simply simply means means that that you you has has reference reference variables, variables, which does not refer to an object. which does not refer to an object.

17 17

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes Classes

Classes Classes can can have have one one or or more more constructors constructors that that are are special special methods methods executed executed when when creating creating Classes can have one or more constructors that are special methods executed when creating an an object object of of the the class. class. A construction is written in in the the same same way way as as other other methods, methods, but but an object of the class. AA construction construction isis written written in the same way as other methods, but the can in the name name is the same same as as the the class, class, and and they they do do not not have have any any type. type. Constructors Constructors can can in in the name isis the the same as the class, and they do not have any type. Constructors principle in the principle perform perform anything, anything, but but they they are are typically typically used used to to initialize initialize instance instance variables variables in in the the principle perform anything, but they are typically used to initialize instance variables class. class. In In this this case, case, the the constructor constructor has has parameters parameters for for an an object’s object’s values. values. These These parameters parameters class. In this case, the constructor has parameters for an object’s values. These parameters have have the the same same names names as as the the instance instance variables variables (it (it is not aaa requirement, requirement, and and the the parameters parameters have the same names as the instance variables (it isis not not requirement, and the parameters must must be be named named anything), anything), and and in in the the constructor’s constructor’s code code there there are are two two things things with with the the same same must be named anything), and in the constructor’s code there are two things with the same name name (both (both an an instance instance variable variable and and aaa parameter). parameter). It solved by by the the word word this this where, where, for for name (both an instance variable and parameter). ItIt is isis solved solved by the word this where, for example example this.name this.name refer refer to to the the instance instance variable, variable, while while name name specific specific the the parameter. parameter. III will will example this.name refer to the instance variable, while name specific the parameter. will insist insist that that aaa specific specific subject subject must must have have both both an an id id and and aaa name. name. Therefore, Therefore, the the constructor constructor insist that specific subject must have both an id and name. Therefore, the constructor tests the constructor raises an exception. tests the the parameters, parameters, and and if they not not both both how how aaa value value the the constructor constructor raises raises an an exception. exception. tests the parameters, and ifif they they not both how value Exceptions Exceptions are are discussed discussed later, later, but but if method as as here here can can raise raise an an exception, exception, the the method method Exceptions are discussed later, but ifif aaa method method as here can raise an exception, the method must must be be marked marked with with throws: throws: must be marked with throws: throws throws Exception Exception

IfIf the the parameters parameters do do not not have have legal legal values, values, raises raises the the constructor constructor an an exception exception if if (!subjectOk(id, (!subjectOk(id, name)) name)) throw new Exception("The throw new Exception("The subject subject must must have have both both an an ID ID and and aa name"); name");

AXA Global Graduate Program Find out more and apply

18 18 18

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes Classes

You should note that the parameters are tested by the method subjectOk(). This method You You should should note note that that the the parameters parameters are are tested tested by by the the method method subjectOk(). subjectOk(). This This method method is defined static, meaning that it can be used without having created an object the isis defined defined static, static, meaning meaning that that itit can can be be used used without without having having created created an an object object ofof of the the class. Other classes can use the method to test values before creating the object. That kind class. class.Other Otherclasses classescan canuse usethe themethod methodtototest testvalues valuesbefore beforecreating creatingthe theobject. object.That Thatkind kind of control methods may be reasonable, if you later find out that the controls should be ofof control control methods methods may may be be reasonable, reasonable, ifif you you later later find find out out that that the the controls controls should should be be different. You should then simply change the method, and it is not necessary to change different. different.You You should should then then simply simply change change the the method, method, and and itit isis not not necessary necessary toto change change elsewhere in the code. elsewhere elsewhereininthe thecode. code. That constructor this way raises an exception guarantee that no one instantiates That Thataaaconstructor constructorinin inthis thisway wayraises raisesan anexception exceptionisis isaaaguarantee guaranteethat thatno noone oneinstantiates instantiates illegal objects – the one that instantiates an object, must necessarily decide what should illegal illegal objects objects –– the the one one that that instantiates instantiates an an object, object, must must necessarily necessarily decide decide what what should should happen in case the object is illegal. However, we can discuss the wisdom of in this way happen happeninincase casethe theobject objectisisillegal. illegal.However, However,we wecan candiscuss discussthe thewisdom wisdomofofininthis thisway waytoto to let constructor validate input parameters and possible raise an exception, and the diskusion let letconstructor constructorvalidate validateinput inputparameters parametersand andpossible possibleraise raisean anexception, exception,and andthe thediskusion diskusion I will return to later. I Iwill willreturn returntotolater. later. this case, the class’s other methods are simple. An object’s must be readable, but InIn Inthis thiscase, case,the theclass’s class’sother othermethods methodsare aresimple. simple.An Anobject’s object’sidid idmust mustbe bereadable, readable,but butitit it must not be changed. Therefore, the class has only a method must mustnot notbe bechanged. changed.Therefore, Therefore,the theclass classhas hasonly onlyaamethod method public String getId() public String getId()

returns the value. Methods which that way just returns the value an instance toto to returns returns the the value. value. Methods Methods which which inin in that that way way just just returns returns the the value value ofof of an an instance instance variable, usually all use this syntax (the variable’s name with the first character in uppercase variable, variable,usually usuallyall alluse usethis thissyntax syntax(the (thevariable’s variable’sname namewith withthe thefirst firstcharacter characterininuppercase uppercase and prefixed with the word get), and you call them for get-methods. Similarly, the variable and andprefixed prefixedwith withthe theword wordget), get),and andyou youcall callthem themfor forget-methods. get-methods.Similarly, Similarly,the thevariable variable name also has a get method, but here it must also be possible to change the name. The name namealso alsohas hasaaget getmethod, method,but buthere hereititmust mustalso alsobe bepossible possibletotochange changethe thename. name.The The class then has a set-method for name: class classthen thenhas hasaaset-method set-methodfor forname: name: public void setName(String name) public void setName(String name)

and methods which in that way only are used to change the value of an instance variable, and and methods methods which which in in that that way way only only are are used used to to change change the the value value of of an an instance instance variable, variable, usually all use this syntax. In this case, the method may raise an exception ififthe name has usually all use this syntax. In this case, the method may raise an exception the name usually all use this syntax. In this case, the method may raise an exception if the name has has an illegal value, but ititisisnot aarequirement that the set-methods may raise an exception. an illegal value, but not requirement that the set-methods may raise an exception. an illegal value, but it is not a requirement that the set-methods may raise an exception. Both the class and its methods are decorated with Java comments. With aa special tool Both Both the the class class and and its its methods methods are are decorated decorated with with Java Java comments. comments. With With a special special tool tool you can from these comments create aa full finished html documentation ofof classes inin aa you can from these comments create full finished html documentation classes you can from these comments create a full finished html documentation of classes in a program. I’ll explain how later, and also what the various descriptions elements means, but program. program. I’ll I’ll explain explain how how later, later, and and also also what what the the various various descriptions descriptions elements elements means, means, but but ininthis case, ititisiseasy enough totofigure out the meaning. IfIfyou place the cursor ininfront this case, easy enough figure out the meaning. you place the cursor front in this case, it is easy enough to figure out the meaning. If you place the cursor in front ofofaamethod and enters of a method method and and enters enters /** /**

plus the Enter key, then NetBeans creates a skeleton for a comment, and one of the plus key, then NetBeans creates aa skeleton for and one plus the the Enter Enter thenway NetBeans creates to skeleton for aa comment, comment, and parameters one of of the the advantages is, thatkey, in that you remember write comments for a method’s advantages is, that in that way you remember to write comments for a method’s parameters advantages is, that in any thatexceptions. way you remember to write comments for a method’s parameters and return value and and return value and any and return value and any exceptions. exceptions.

19 1919

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes

Objects Objectsmust mustbebecreated createdororinstantiated, instantiated,which whichisisdone donewith withnew: new: package students; public class Students { public static void main(String[] args) { try { Subject subject = new Subject("MAT7", "Matematichs"); System.out.println(subject); subject.setName("Matematichs 7"); System.out.println(subject); } catch (Exception ex) { System.out.println(ex.getMessage()); } } }

The Theprogram programcreates createsananobject objectsubject subjectofofthe thetype typeSubject. Subject.When Whenthe theconstructor constructorininthe theclass class Subject Subjectmay mayraise raiseananexception, exception,ititshould shouldbebehandled, handled,and andititisisnecessary necessarytotoplace placethe thecode code that thatmay mayraise raiseananexception exceptioninina atry/catch. try/catch.After Afterthe theobject objectisiscreated, created,ititisisprinted printedon onthe the screen. screen.IfIfyou youprints printsananobject objectwith withprintln(), println(),ititisisthe thevalue valueofofthe theobject’s object’stoString() toString()method method that thatisisprinted. printed.InInprinciple, principle,allallclasses classeshas hasa atoString() toString()method methodwhich whichreturns returnsa atext textthat that represents representsa aparticular particularobject. object.Finally Finallythe theprogram programchanges changesthe thename nameofofthe thesubject, subject,and and the theobject objectisisprinted printedagain. again. The Theclasses classes(Subject (Subjectand andStudents) Students)described describedabove abovecan canbebefound foundininthe theproject projectStudents1. Students1.

EXERCISE EXERCISE11 Create Createa anew newproject projectininNetbeans Netbeansthat thatyou youcan cancall callLibrary. Library.You Youmust mustadd adda aclass classthat that should shouldbebecalled calledPublisher Publisherthat thatrepresents representsa abook bookpublisher publisherwhen whenthe thepublisher publishermust musthas has the thefollowing followingtwo twoproperties: properties: 1. 1.ananinteger, integer,that thatyou youcan cancall callcode codewhich whichisistotobebeinterpreted interpretedasasa apublisher publisheridentifier identifier 2. 2.a aname, name,that thatjust justisisa atext textand andisisthe thepublishers publishersname name

20 20

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes

ItIt isis aa requirement requirement that that the the publisher publisher number number isis aa positive positive integer integer and and that that aa publisher publisher must must have have aa name. name. The The class class must must have have aa constructor constructor that that has has parameters parameters for for both both variables variables and and has has the the following following public public methods: methods: --- get get methods methods to to both both variables variables --- aa set set method method to to the the publishers publishers name name --- aa toString() toString() method method that that returns returns the the publishers publishers name name followed followed by by the the publisher publisher number number in in square square brackets brackets When Whenyou youhave havewritten writtenthe theclass, class,you youmust mustdocument documentititand andits itsmethods methodsusing usingJava Javacomments. comments. Finally, Finally, in in the the main main class class –– that that class class Library Library –– you you should should write write aa main() main() method method that that ---------

Creates Creates aa Publisher Publisher object object –– you you decide decide the the values values Prints Prints the the publisher publisher Change Change the the publishers publishers name name Prints Prints the the publisher publisher again again

IfIf you you executes executes the the program, program, the the result result could could be be the the following: following: The new Publisher [123] The old Publisher [123]

I joined MITAS because I wanted real responsibili� I joined MITAS because I wanted real responsibili�

Real work International Internationa al opportunities �ree wo work or placements

21 21

�e Graduate Programme for Engineers and Geoscientists

Maersk.com/Mitas www.discovermitas.com

�e G for Engine

Ma

Month 16 I was a construction Mo supervisor ina const I was the North Sea super advising and the No he helping foremen advis ssolve problems Real work he helping fo International Internationa al opportunities �ree wo work or placements ssolve pr

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes

2.1 2.1 MORE MORE CLASSES CLASSES II will will then then look look at at aa class class representing representing aa subject subject that that aa student student has has completed completed or or participate participate in. in. ItIt isis assumed assumed for for simplicity simplicity that that the the same same subjects subjects only only can can be be performed performed once once aa year year and and therefore therefore are are identified identified the the subject’s subject’s id id and and the the year. year. The The project project isis called called Students2 Students2 and and isis created created as as aa copy copy of of Strudents1. Strudents1. There There isis added added the the class class Course Course as as shown shown below, below, and and again again explains explains the the comments comments of of the the individual individual methods methods there there purposes: purposes: package students; /** * Class that represents a course, where a course regarding a year and a subject. * A student may have completed or attend a particular course. * It is an assumption that the same subjects only be executed once a year. * A course can also be associated with a character. If so, it means that * the student has completed the course. */ public class Course { // year of when the course is completed or offered private int year; // the subject that the course deals private Subject subject; // the character tkhat a student has obtained in the subject private int score = Integer.MIN_VALUE; /** * Creates a course for a concrete subjects and a given year. * @param year The year for the course * @param subject The subject for this course * @throws Exception If the year is illegal or the subject is null */ public Course(int year, Subject subject) throws Exception { if (!courseOk(year, subject)) throw new Exception("Illegal course"); this.year = year; this.subject = subject; } /** * A cource is identified by the subjects id and the year * @return ID composed of the year of the subject's id separated by a hyphen */ public String getId() {

22 22

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

return year + "-" + subject.getId();

} /** * @return The year where the course is held. */ public int getYear() { return year; } /** * @return true, if the student has completed the course */ public boolean completed() { return score > Integer.MIN_VALUE; } /** * @return The character that the student has achieved * @throws Exception If a student has not obtained a character */ public int getScore() throws Exception { if (score == Integer.MIN_VALUE) throw new Exception("The student has not completed the course"); return score; } /** * Assigns this course a score. * @param score The score that is the obtained * @throws Exception If the score is illegal */ public void setScore(int score) throws Exception { if (!scoreOk(score)) throw new Exception("Illegal ckaracter"); this.score = score; } /** * Assigns this course a character. * @param score The score that is the obtained * @throws Exception If the score is illegal */ public void setScore(String score) throws Exception { try {

23 23

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

int number = Integer.parseInt(score); if (!scoreOk(number)) throw new Exception("Illegal score"); this.score = number;

}

} catch (Exception ex) { throw new Exception("Illegal score"); }

/** * @return The course's subject */ public String toString() { return subject.toString(); } /** * Tests whether the parameters for a course are legal * @param year The year for the course * @param subject The subject that this course deals * @return true, If the year is illegal or the subject is null

93%

OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION

MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE

5 Specializations

Personalize your program

www.ie.edu/master-management

#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES

[email protected]

24 24

Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

*/ public static boolean courseOk(int year, Subject subject) { return year >= 2000 && year < 2100 && subject != null; }

}

// Validates whether a character is legal private boolean scoreOk(int score) { return true; }

The class looks like the class Subject, but there are still things that you should note. The class has three instance variables, and one of the type Subject. You should therefore note that the type of an instance variable may well be a user-defined type and here a class. There is also an instance variable called year that has the type int. There is a variable score, that should be applied to the score which a student has achieved in the subject. In one way or another it should be possible to indicate that a student has not yet been given a score, for example because the course has not been completed. This is solved by assigning the variable the value Integer.MIN_VALUE which is the least 32-bit integer that can occur. This number is -2147483648, and one must assume that this score can not occur in a character system. Note that wee in Java uses the same rules and conventions for method names that wee use for variables and such should the name of a method to start with a lowercase letter. The method setScore(), which assigns a course a character is available in two versions. In Java, a method is identified by its name and its parameters. There may well in the same class be two methods with the same name as long as they have different parameters, that is when the parameter lists can be separated either on the parameter types or the number of parameters. It is sometimes said that the methods can be overloaded. In this case, as mentioned, there are two versions of the method setScore(), one with an int as a parameter, while the other has a String. So you can specify a character as both an int and a String, and the possibility is included only to illustrate the concept of function overloading. When you assign a course a score it is validated by the method scoreOk(). This method is trivial, since it always returns true, and it provides little sense. The goal is that the method at a later time should be changed to perform something interesting, and you can say that the problem is that the class Course not have knowledge of what is legal scores. There are several grading systems.

25 25

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes

Now NowI Ihave havedefined definedtwo twoclasses classesregarding regardingstudents, students,and andthere thereisisaaconnection connectionbetween betweenthe the two classes so that the class Course consist of an object of the class Subject. It is sometimes two classes so that the class Course consist of an object of the class Subject. It is sometimes illustrated illustratedasas

IfIfyou youhave havetotocreate createaaCourse, Course,you youmust mustprovide provideaayear yearand andaaSubject, Subject,which whichisisan anobject object that thatmust mustalso alsobe becreated. created.IfIfyou youfind findititappropriate, appropriate,you youcan canadd addan anadditional additionalconstructor constructor that creates this object: that creates this object: /** * Creates a course for a concrete subjects and a given year. * @param year The year for the course * @param id The subject's id * @param name The subject's name * @throws Exception If the year is illegal or id and name are not legal */ public Course(int year, String id, String name) throws Exception { subject = new Subject(id, name); if (!courseOk(year, subject)) throw new Exception("Illegal year"); this.year = year; }

You Youmust mustspecifically specificallynote notethat thatififthe theclass classSubject Subjectraises raisesan anexception exception(the (theconstructor constructorofof the theclass classSubject) Subject)when whenthe theobject objectisiscreated, created,then thenthe theabove aboveconstructor constructorisisinterrupted interruptedby by sending sendingthe theexception exceptionobject objectfrom fromthe theclass classSubject Subjecton ontotothe thecalling callingcode. code.Constructors Constructors can thus be overloaded by the exact same rules as for other methods. can thus be overloaded by the exact same rules as for other methods. Below Belowisisaamethod methodthat thatcreates createstwo twocourses: courses: private static void test1() { try { Course course1 = new Course(2015, new Subject("MAT6", "Matematik 6")); Course course2 = new Course(2015, "MAT7", "Matematik 7"); course1.setScore(7); print(course1); print(course2); } catch (Exception ex)

26 26

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

{ }

}

Classes Classes

System.out.println(ex.getMessage());

private static void print(Course course) throws Exception { System.out.println(course); if (course.completed()) System.out.println("The course is completed with the result " + course.getScore()); }

Note Note how how to to create create objects objects of of the the type type Course Course and and how how the the two two different different constructors constructors are are used. You should note that the method getScore() may raise an exception. Therefore, the used. You should note that the method getScore() may raise an exception. Therefore, the print() print() method method may may raise raise an an exception, exception, and and ifif itit happens happens the the method method will will be be interrupted interrupted and the Exception object is passed on to the method test1(). Also note how in and the Exception object is passed on to the method test1(). Also note how in the the print() print() method you refers to methods in the Course class using the dot operator on the method you refers to methods in the Course class using the dot operator on the course course object, and that the methods works on the specific Course object’s state. object, and that the methods works on the specific Course object’s state.

27 27

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes

II will will then then look look at at aa class class that that represents represents aa student. student. A A student student must must in in this this example example alone alone have have aa mail mail address address and and aa name, name, and and also also aa student student could could have have aa number number of of courses courses that that the the student student has has either either completed completed or or participates participates in. in. This This can can be be illustrated illustrated as as follows: follows:

where where ** indicates indicates that that aa student student may may be be associated associated with with many many Course Course objects. objects. The The class class isis shown shown below, below, and and itit takes takes up up aa lot lot particular particular because because of of the the comments, comments, but but to to emphasize emphasize that that classes classes should should be be documented documented by by comments, comments, II have have chosen chosen to to retain retain them, them, and and they they also also helps helps to to explain explain the the meaning meaning of of class’s class’s methods: methods: package students; import java.util.*; /** * The class represents a student when a student is characterized by a mail * address. * As a unique identifier is used, a number that is automatically incremented * by 1 each time a new object is created. * A student has a list of courses that the student has completed or * participate in. */ public class Student { private static int nummer = 0; // the last used id private int id; // the students id private String mail; // the student's mailadresse private String name; // the student's name private ArrayList courses = new ArrayList(); // a list with courses /** * Creates a new student from an array of courses. * @param mail The student's mail address * @param name The student's name * @param course An array with courses * @throws Exception If the mail or the name does not represents legal values */ public Student(String mail, String name, Course … course) throws Exception { if (!studentOk(mail, name)) throw new Exception("Ulovlig værdier for en studerende");

28 28

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

this.mail = mail; this.name = name; for (Course c : course) courses.add(c); id = ++nummer;

} static { nummer = 1000; }

/** * @return The student's id */ public int getId() { return id; } /** * @return The students mail address */ public String getMail() { return mail; } /** * Changes the mail address on a student. * @param mail The student's mail address * @throws Exception If no legal mail address is specified */ public void setMail(String mail) throws Exception { if (mail == null || mail.length() == 0) throw new Exception("Illegal mail adresse"); this.mail = mail; } /** * @return The student's name */ public String getName() { return name; }

29 29

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

/** * Changing the name of a student. * @param name The student's name * @throws Exception If no name is specified */ public void setName(String name) throws Exception { if (name == null || name.length() == 0) throw new Exception("Illigal name"); this.name = name; } /** * @return Number of courses that this student has completed or participated in */ public int getCount() { return courses.size(); } /** * Returns the n'th course for this student * @param n Index of the desired course * @return The nth course like this student has completed or participated in

Excellent Economics and Business programmes at:

“The perfect start of a successful, international career.” CLICK HERE

to discover why both socially and academically the University of Groningen is one of the best places for a student to be

www.rug.nl/feb/education

30 30

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

* @throws Exception If the is illegal */ public Course getCourse(int n) throws Exception { return courses.get(n); } /** * @param id Identifier of a course * @return Teh course identified by id * @throws Exception If the course is not found */ public Course getKursus(String id) throws Exception { for (Course c : courses) if (c.getId().equals(id)) return c; throw new Exception("Course not found"); } /** * Returns the courses that the current student have completed or participated * in a particular year. * @param year The year searching for * @return Course list of discovered courses */ public ArrayList getCourses(int year) { ArrayList list = new ArrayList(); for (Course c : courses) if (c.getYear() == year) list.add(c); return list; } /** * Adds a course for the students. * @param course The course to be added * @throws Exception If the list already have the same course */ public void add(Course course) throws Exception { for (Course c : courses) if (course.getId().equals(c.getId())) throw new Exception("The course is already added"); courses.add(course); } /** * @return Returns the student's id address and name

31 31

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Classes Classes

*/ public String toString() */ { public String toString() return "[" + id + "] " + name; { } return "[" + id + "] " + name; } /** * Tests whether the mail and name to represent a student. /** * @param mail A student's mail address * Tests whether the mail and name to represent a student. * @param name A student's name * @param mail A student's mail address * @return true, if mail and name represents a legal student * @param name A student's name */ * @return true, if mail and name represents a legal student public static boolean studentOk(String mail, String name) */ { public static boolean studentOk(String mail, String name) // the control is simple and should be extended to check whether mail has a { // proper format for an email address // the control is simple and should be extended to check whether mail has a return mail != null && mail.length() > 0 && name != null && name.length() > 0; // proper format for an email address } return mail != null && mail.length() > 0 && name != null && name.length() > 0; } }

The Theclass classStudent Studentrepresents representsaastudent. student.The Theclass classhas hasfour fourinstance instancevariables, variables,where wherethe thefirst first isisan identifier (a number), next are ofofthe type String isisrespectively the mail an identifier number),athe the nexttwo two thefour typeinstance Stringand and respectively thefirst mail The class Student (a represents student. The are class has variables, where the address and student’s The last is of the type ArrayList, and be andthe the student’sname. name. thetype typeString ArrayList, andshould should is address an identifier (a number), the nextThe twolast areisofofthe and is respectively the mailbe used the that student has completed ororparticipates in. constructor usedtotoand thecourses courses thatthe the student participates in.The Theclass’s class’s constructor address the student’s name. The has last completed is of the type ArrayList, and should be raises an exception ififthe parameters are not legal. The class’s other methods require no raises an exception the parameters are not legal. The class’s other methods require used to the courses that the student has completed or participates in. The class’s constructorno special explanation, but note, however, that the method getCourses() isisoverloaded. special however, method getCourses() overloaded. raises an explanation, exception if but the note, parameters are that not the legal. The class’s other methods require no special explanation, but note, however, that the method getCourses() is overloaded. An Anobject objecthas hasaavariable variableid, id,which whichisisaanumber numberthat thatcan canidentify identifyaastudent. student.This Thisnumber number is automatically assigned in the starting with 1001 such that the automatically assigned the constructor constructor 1001aand and suchThis thatnumber the next next Anis object has a variable id, in which is a numberstarting that canwith identify student. student isisassigned the number. How works, I Iwill return totowhen I Italk assigned thenext next number. Howitstarting itexactly exactlywith works, will talk is student automatically assigned in the constructor 1001 and return such thatwhen the next about members. aboutstatic static members. student is assigned the next number. How it exactly works, I will return to when I talk about static members. Below Belowisisaamethod, method,which whichcreates createstwo twostudents: students: Below is a method, which creates two students:

private static void test2() { private static void test2() try { { try Student stud1 = new Student("[email protected]", "Svend Andersen"); { Student stud2 = new Student("[email protected]", "Gorm Madsen", Student stud1 = new Student("[email protected]", "Svend Andersen"); new Course(2015, new Subject("PRG", "Programming")), Student stud2 = new Student("[email protected]", "Gorm Madsen", new Course(2015, new Subject("OPS", "Operating systems"))); new Course(2015, new Subject("PRG", "Programming")), stud1.add(new Course(2014, new Subject("DBS", "Database Systems"))); new Course(2015, new Subject("OPS", "Operating systems"))); stud2.add(new Course(2014, new Subject("WEB", "Web applicattions"))); stud1.add(new Course(2014, new Subject("DBS", "Database Systems"))); stud2.add(new Course(2014, new Subject("WEB", "Web applicattions")));

32 32 32

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

stud1.getCourses("2014-DBS").setScore(4); stud2.getCourses("2014-WEB").setScore(10); stud2.getCourses("2015-OPS").setScore(2); print(stud1); print(stud2);

}

} catch (Exception ex) { System.out.println(ex.getMessage()); }

private static void print(Student stud) { System.out.println(stud); for (int i = 0; i < stud.getCount(); ++i) { try { Course c = stud.getCourse(i); System.out.println(c + ", " + (c.completed() ? "Score: " + c.getScore() : "Not completed")); }

American online LIGS University is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and ▶▶ save up to 16% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!

Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.

33 33

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

} }

} }

Classes Classes Classes

catch (Exception ex) catch (Exception ex) { { } }

The Thefirst firststudent studentisiscreated createdwithout withoutspecifying specifyingcourses. courses.The Theother otherstudent studentisiscreated createdwith with The first student is created without specifying courses. The other student is created with two courses. Next, the program adds a course to both students and finally assigns scores two courses. Next, the program adds a course to both students and finally assigns scores twothree courses. Next, the program adds a course to both method students and finally the assigns scores for for threecourses, courses,and andthe thetwo twostudents studentsare areprinted. printed.The The methodisisexecuted, executed, theresult resultis:is: for three courses, and the two students are printed. The method is executed, the result is: [1001] Svend Andersen [1001] Svend Andersen Database Systems, Score: 4 Database Systems, Score: 4 [1002] Gorm Madsen [1002] Gorm Madsen Programming, Not completed Programming, Not completed Operating systems, Score: 2 Operating systems, Score: 2 Web applicattions, Score: 10 Web applicattions, Score: 10

EXERCISE22 EXERCISE EXERCISE 2 Thisexercise exercise is a continuationofofexercise exercise 1. Startby by makinga acopy copy of theproject project Libraryasas This This exerciseisisa acontinuation continuation of exercise1.1.Start Start bymaking making a copyofofthe the projectLibrary Library as youcan cancall callLibrary1 Library1and andopen openthe thecopy copyininNetBeans. NetBeans.You Youmust mustadd adda aclass classnamed namedAuthor. Author. you you can call Library1 and open the copy in NetBeans. You must add a class named Author. Theclass class shouldhave have threeinstance instance variables The The classshould should havethree three instancevariables variables 1.ididwhich which is an integer,that that canidentify identify an author 1. 1. id whichisisananinteger, integer, thatcan can identifyananauthor author 2.firstname firstnamefor forthe theauthor’s author’sfirst firstname name 2. 2. firstname for the author’s first name 3.lastname lastname forthe the author’slast last name 3. 3. lastnamefor for theauthor’s author’s lastname name is a requirementthat not null,but but it is allowedtotobebeblank. blank. Onthe the that thefirst first nameisisnot ItIt Itisisa arequirement requirement thatthe the firstname name is notnull, null, butititisisallowed allowed to be blank.On On the otherhand, hand, an authormust must havea alast last name. other other hand,ananauthor author musthave have a lastname. name. Theclass class shouldhave which hastwo two parameters,respectively respectively to initialize have a constructor,which The The classshould should havea aconstructor, constructor, whichhas has twoparameters, parameters, respectivelytotoinitialize initialize firstnameand andlastname. lastname.AAauthor’s author’sididshould shouldbebeassigned assignedautomatically, automatically,sosothat thatevery everytime time firstname firstname and lastname. A author’s id should be assigned automatically, so that every time newAuthor Author is createdthe the objectget get an id,which which is onegreater greater thanthe the previousone. one. a aanew new Authorisiscreated created theobject object getananid, id, whichisisone one greaterthan than theprevious previous one. Youcan can solvethis this a staticvariable: variable: You You cansolve solve thisa astatic static variable: private static int counter = 0; private static int counter = 0;

whichisiscounted counted upby by 1 eachtime time a newAuthor Author is created. which which is countedup up by11each each timea anew new Authorisiscreated. created. Regardingthe the methods,the get methodfor for all thethree three variables,and and a the classmust must havea aget Regarding Regarding themethods, methods, theclass class musthave have a getmethod method forallallthe the threevariables, variables, anda a methodfor for bothfirstname firstname andthe the lastname.Finally, Finally, theremust must be a toString()method method setset setmethod method forboth both firstnameand and thelastname. lastname. Finally,there there mustbebea atoString() toString() method thatreturns returns an author’sfirst first andlast last nameseparated separated bya aspace. space. that that returnsananauthor’s author’s firstand and lastname name separatedby by a space.

34 34

JAVA JAVA3: OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA 3:3:OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING

Classes Classes Classes

Once Onceyou youhave havewritten writtenthe theclass, class,you youmust mustdocument documentit usingJava Javacomments. comments. Once you have written the class, you must document ititusing using Java comments. In themain mainclass, class,write writeaaamethod methodthat thatcan canprint printan anAuthor   Author:: : InInthe the main class, write method that can print an Author private static static void void print(Author print(Author a) a) private

when whenthe themethod methodshould shouldprint printthe theauthor’s author’sid listedin brackets,as wellas theauthor’s author’sfirst first when the method should print the author’s ididlisted listed ininbrackets, brackets, asaswell well asasthe the author’s first and andlast lastname. name.Write Writethe themain() main()method methodso performsthe thefollowing: following: and last name. Write the main() method sosoit ititperforms performs the following: ----------------

creates createstwo twoauthors authors–––you youdecides decidesthe thenames names creates two authors you decides the names prints the two authors printsthe thetwo twoauthors authors prints change changethe thefirst firstname nameof thefirst firstauthor author change the first name ofofthe the first author change changethe thelast lastname nameof theother otherauthor author change the last name ofofthe the other author prints printsthe thetwo twoauthors authorsagain again prints the two authors again

If youexecutes executesthe theprogram programthe theresult resultcould couldbe: be: IfIfyou you executes the program the result could be: [1] Gudrun Gudrun Jensen Jensen [1] [2] Karlo Andersen [2] Karlo Andersen [1] Abelone Abelone Jensen Jensen [1] [2] Karlo Kristensen [2] Karlo Kristensen

EXERCISE EXERCISE33 Make Makeaacopy copyofofthe theproject projectLibrary1 Library1and andcall callthe thecopy copyLibrary2. Library2.Open OpenititininNetBeans. NetBeans.Add Add aaclass classBook Bookthat thatrepresents representsaabook bookwith withthe thefollowing followingcharacteristics: characteristics: ---------------

Isbn, Isbn,that thatmust mustbe bedeclared declared Title, Title,that thatmust mustbe bedeclared declared Publisher Publisheryear, year,there theremust mustbe be00ororlie liebetween between1900 1900and and2100, 2100,00indicates indicatesthat that publisher publisheryear yearisisunknown unknown Edition, Edition,which whichmust mustbe bebetween between00and and15 15(inclusive), (inclusive),00indicates indicatesthat thatthe theedition edition isisunknown unknown Number Numberofofpages pagesthat thatmust mustbe benon-negative, non-negative,00indicates indicatesthat thatnumber numberofofpages pages are areunknown unknown Publisher, Publisher, there there must must be be aa Publisher Publisher object object oror null, null, where where null null means means that that the the publisher publisherisisunknown unknown AAnumber numberofofauthors, authors,there theremust mustAuthor Authorobjects objects(the (thenumber numberafafauthors authorsmust mustbe be 00ififno noauthors authorsare areknown) known)

3535 35

JAVA PROGRAMMING JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING

Classes Classes

The constructors with with the the following following signatures: signatures: The class class must must have have four four constructors public Book(String isbn, String title) throws Exception { … } public Book(String isbn, String title, int released) throws Exception { … } public Book(String isbn, String title, Publisher publisher) throws Exception { … } public Book(String isbn, String title, int released, int edition, int pages, Publisher publisher) throws Exception { … }

36

36

JAVA JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes Classes

There There must be get methods for all of the above fields, and there must be set methods to the There must be get methods for all of the above fields, and there must be set methods to the Theremust mustbe beget getmethods methodsfor forall allof ofthe theabove abovefields, fields,and andthere theremust mustbe beset setmethods methodsto tothe the fields title, released, edition, pages and publisher. fields fields title, title, released, released, edition, edition, pages pages and and publisher. publisher. As As for authors the class should in the same manner the class Student have an ArrayList Asfor forauthors authorsthe theclass classshould shouldin inthe thesame samemanner mannerasas asthe theclass classStudent Studenthave havean anArrayList ArrayList the the Author objects: the Author objects: theAuthor Authorobjects: objects: private private ArrayList ArrayList authors authors == new new ArrayList(); ArrayList();

The The class Book should have toString() method must return the book’s ISBN and the title Theclass classBook Bookshould shouldhave haveaaatoString() toString()method methodmust mustreturn returnthe thebook’s book’sISBN ISBNand andthe thetitle title separated by a space. Finally, there must be a static method: separated separated by by aa space. space. Finally, Finally, there there must must be be aa static static method: method: public public static static boolean boolean isbnOk(String isbnOk(String isbn) isbn)

that that validates an isbn, when so far only should test that the parameter not an empty string. thatvalidates validatesan anisbn, isbn,when whenitititso sofar faronly onlyshould shouldtest testthat thatthe theparameter parameterisisisnot notan anempty emptystring. string. Once Once you have written the class, you must document and its methods. Onceyou youhave havewritten writtenthe theclass, class,you youmust mustdocument documentitititand andits itsmethods. methods. In In the main class, write method that can create and return Book object from information Inthe themain mainclass, class,write writeaaamethod methodthat thatcan cancreate createand andreturn returnaaaBook Bookobject objectfrom frominformation information on on the book’s properties: on the book’s properties: onthe thebook’s book’sproperties: properties: private private static static Book Book create(String create(String title, title, int int released, released, int int edition, edition, int int pages, pages, Publisher Publisher publisher, publisher, {{ }}

isbn, isbn, String String Author Author …… authors) authors) throws throws Exception Exception

You must then write method that can print book: You Youmust mustthen thenwrite writeaaamethod methodthat thatcan canprint printaaabook: book: private private static void print(Book book) {} private static static void void print(Book print(Book book) book) {} {}

when has to print whenititithas hasto toprint print when ------------------------

the book’s ISBN the book’s ISBN the thebook’s book’sISBN ISBN the book’s title thebook’s book’stitle title the the book’s publisher year known thebook’s book’spublisher publisheryear yearifififknown known the the book’s edition known thebook’s book’sedition editionifififknown known the the book’s number of pages known the book’s number of pages known the thebook’s book’snumber numberof ofpages pagesififif ifknown known the book’s publisher known thebook’s book’spublisher publisherifififknown known the the book’s authors there are authors thebook’s book’sauthors authorsifififthere thereare areauthors authors the

37 37 37 37

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

You Youmust mustfinally finallywrite writethe themain() main()method, method,sosoititperforms performsthe thefollowing: following: You must finally write the main() method, so it performs the following: --- create createaabook bookusing usingthe theabove abovemethod methodwhere whereyou youspecify specifyvalues valuesfor forall allthe thebook’s book’s - fields create a book using above method where you specify values for all the book’s and including the book’s author(s) fields and including the book’s author(s) fields including author(s)the --- create aabook where you only createand book wherethe youbook’s onlyinitialize initialize thebook’s book’sISBN ISBNand andtitle title create a book where you only initialize the book’s ISBN and title --- prints the two books prints the two books prints books year, --- change the publisher changethe thetwo publisher year,edition, edition,number numberofofpages pagesand andthe thepublisher publisherfor forthe thelast last - book change the publisher year, edition, number of pages and the publisher for the last and adds the author(s) book and adds the author(s) book the author(s) --- prints the last again printsand theadds lastbook book again - prints the last book again The Theresult resultcould, could,for forinstance instancebe beasasshown shownbelow: below: The result could, for instance be as shown below: ISBN: 978-1-59059-855-9 ISBN: 978-1-59059-855-9 Title: Beginning Fedora From Noice to Professional Title: Beginning Fedora From Noice to Professional Released: 2007 Released: 2007 Edition: 1 Edition: 1519 Pages Pages Publisher: 519 The new Publisher [123] Publisher: The new Publisher [123] Authors: Authors: [1] Shashank Sharma [1] Sharma [2] Shashank Keir Thomas [2] Keir Thomas ISBN: ISBN: Title: Title: ISBN: ISBN:

978-87-400-1676-5 978-87-400-1676-5 Spansk Vin Spansk Vin 978-87-400-1676-5 978-87-400-1676-5

Title: Spansk Vin Title: Spansk Released: 2014 Vin Released: 2014 Edition: 1 Edition: 1335 Pages Pages Publisher: 335 Politikkens Forlag [200] Publisher: Politikkens Forlag [200] Authors: Authors: [3] Thomas Rydberg [3] Thomas Rydberg

PROBLEM 1 PROBLEM PROBLEM 1 1

A book is characterized by an ISBN, which is an international numbering on 10 or 13 A book is by which is international numbering on 10 13 Adigits. bookThe is characterized characterized by an an ISBN, ISBN, which is an an international 10 or or 13 system was introduced around 1970, and until 2007 itnumbering was on 10on digits, which digits. The system was introduced around 1970, and until 2007 it was on 10 digits, which digits. The system was introduced aroundby1970, and until 2007 it was on 10 digits, which was divided into four groups separated hyphens: was divided into four groups separated by hyphens: was divided into four groups separated by hyphens: 99-999-9999-9 99-999-9999-9

38 38

JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA

Classes Classes

wherein the the last last group group always always consists consists of of aa single single digit digit (character) (character) and and is is aa control control character. character. wherein The other three groups are interpreted as follows: 1. the the 1. 2. the the 2. 3. the 3.

first group group is is aa country first country code code second group group is is the the publisher publisher identifier identifier second third group is the title number

The control control character character is is calculated calculated by by the the modulus modulus 11 11 method, method, using using the the weights weights 10, 10, 9, 9, 8, 8, The 7, 6, 6, 5, 5, 4, 4, 3, 3, 2 2 and and 1. 1. This This is is best best explained explained with with an an example. example. Consider Consider aa concrete concrete ISBN: ISBN: 7, 1-59059-855-5

To determine the the check character character you determine determine the To the following following weighted weighted sum: sum: 1 10

5 9

9 8

0 7

5 6

9 5

8 4

5 3

5 2

10 + 45 + 72 + 0 + 30 + 45 + 32 + 15 + 10 = 259

.

39 39 39

JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes Classes

Younow now determinesthe the restby by dividingby by 11and and youget get You You nowdetermines determines therest rest bydividing dividing by11 11 andyou you get 259 %% 11 11 = 6 259 259 % 11 == 66

thisrest restisis0,0,the thecheck checkdigit digitisis0.0.IfIfthe theremainder remainderisis10, 10,XXisisthe thecheck checkcharracter, charracter,and and IfIf this Ifthis thisrest restisis0,0,the thecheck checkdigit digitisis0.0.IfIfthe theremainder remainderisis10, 10,XXisisthe thecheck checkcharracter, charracter,and and If otherwise,one oneuses uses11 11minus minusthe theremainder remainderasascheck checkdigit. digit.As Asthe therest restthis thistime timeisis6,6,you you otherwise, otherwise,one oneuses uses11 11minus minusthe theremainder remainderasascheck checkdigit. digit.As Asthe therest restthis thistime timeisis6,6,you you otherwise, getcheck check11 11––66==5.5. get getcheck check11 11––66==5.5. get Eventuallyititwas wasrealized realizedthat thatby bythe theyears yearsthere therevould vouldbe betoo toofew fewISBN ISBNnumbers, numbers,and and Eventually Eventuallyititwas wasrealized realizedthat thatby bythe theyears yearsthere therevould vouldbebetoo toofew fewISBN ISBNnumbers, numbers,and and Eventually thereforeititwas wasdecided decidedtotochange changethe thesystem systemfrom from2007. 2007.From Fromthat thattime timethe thenumbers numbersare are therefore thereforeititwas wasdecided decidedtotochange changethe thesystem systemfrom from2007. 2007.From Fromthat thattime timethe thenumbers numbersare are therefore precededby byaa3-digit 3-digitprefix, prefix,and andthe thenumbers numbersthus thuscame cametotoconsist consistofofanother anothergroup, group,that that preceded precededby bya a3-digit 3-digitprefix, prefix,and andthe thenumbers numbersthus thuscame cametotoconsist consistofofanother anothergroup, group,that that preceded always has 3 digits: always has digits: alwayshas has333digits: digits: always 999-99-999-9999-9 999-99-999-9999-9 999-99-999-9999-9

So Sofar faronly onlyof ofthe thenumbers numbers978 978and and979 979are areused usedas asprefixes, prefixes,but butin inthe thefuture futurethere therewill will So Sofar faronly onlyofofthe thenumbers numbers978 978and and979 979are areused usedasasprefixes, prefixes,but butininthe thefuture futurethere therewill will probably probablybe beother otheropportunities. opportunities.In Inaddition additionto toincreasing increasingthe thenumbers numberswith withthis thisprefix prefixthe the probably be other opportunities. In addition to increasing the numbers with this prefix the probably be other opportunities. In addition to increasing the numbers with this prefix the calculation calculationof ofthe thecontrol controlcharacter characterwas wasalso alsochanged, changed,so sothat thatas asweights weightsusing usingalternating alternating calculation calculationofofthe thecontrol controlcharacter characterwas wasalso alsochanged, changed,sosothat thatasasweights weightsusing usingalternating alternating values of 1 and 3, and the control character is then the modulus 10 of the weighted sum. values of 1 and 3, and the control character is then the modulus 10 of the weighted sum. values valuesofof11and and3,3,and andthe thecontrol controlcharacter characterisisthen thenthe themodulus modulus10 10ofofthe theweighted weightedsum. sum. Again, Again,it itis iseasiest easiestto toillustere illusterethe thecalculations calculationswith withan anexample. example.Consider Consider Again, it is easiest to illustere the calculations with an example. Consider Again, it is easiest to illustere the calculations with an example. Consider 978-1-59059-855-9 978-1-59059-855-9 978-1-59059-855-9

Youcalculate calculatethe thefollowing followingweighted weightedsum: sum: You You calculate the following weighted sum: 99 9 11 1

77 7 33 3

88 8 11 1

11 1 33 3

55 5 11 1

99 9 33 3

00 0 11 1

55 5 33 3

99 9 11 1

88 8 33 3

55 5 11 1

55 5 33 3

+ 21 ++ 88 ++ 33 ++ 55 ++ 27 27 + 0 + 15 ++ 99 ++ 24 24 + 5 + 15 == 141 141 99 9 ++ 21 21 + 8 + 3 + 5 + 27 ++ 00 ++ 15 15 + 9 + 24 ++ 55 ++ 15 15 = 141

Thenyou youcalculate calculaterest restat atdivision divisionby by10: 10: Then Then Thenyou youcalculate calculaterest restatatdivision divisionby by10: 10: 141% %10 10===111 141 141 141%%10 10 = 1 thisremainder remainderis is0,0,it itisiscontrol controlcharacter. character.Or Oris isthe thecheck checkdigit digit10 10minus minusthe theremainder, remainder, IfIf this If Ifthis thisremainder remainderisis0, 0,ititis iscontrol controlcharacter. character.Or Orisisthe thecheck checkdigit digit10 10minus minusthe theremainder, remainder, and in this case, it is 10 – 1 = 9. and in this case, it is 10 – 1 = 9. and andininthis thiscase, case,ititisis10 10––11==9.9. Youmust mustnow nowreturn returnto tothe theproject projectLibrary Libraryand andthe theclass classBook. Book.Start Startby bycreating creatingaaacopy copy You You Youmust mustnow nowreturn returntotothe theproject projectLibrary Libraryand andthe theclass classBook. Book.Start Startby bycreating creating acopy copy of the project Library2 and call the copy Library3. Open the copy in NetBeans. The class ofofthe the project Library2 and call the copy Library3. Open the copy ininNetBeans. NetBeans. The class of theproject projectLibrary2 Library2and andcall callthe thecopy copyLibrary3. Library3.Open Openthe thecopy copyin NetBeans.The Theclass class Book has a static method isbnOk() to validate whether a string is a legal ISBN. The control Book has a static method isbnOk() to validate whether a string is a legal ISBN. The control Book Bookhas hasa astatic staticmethod methodisbnOk() isbnOk()totovalidate validatewhether whethera astring stringisisa alegal legalISBN. ISBN.The Thecontrol control is trivial, but you must now change the code to validate an ISBN folowing the above rules. is trivial, but you must now change the code to validate an ISBN folowing the above rules. isistrivial, trivial,but butyou youmust mustnow nowchange changethe thecode codetotovalidate validateananISBN ISBNfolowing folowingthe theabove aboverules. rules.

40 40 40 40

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes Classes

You Youmust mustalso alsowrite writeaatest testmethod methodthat thattests testswhether whetherthe thecontrol controlmethod methodvalidates validatescorrectly. correctly. You must also write a test method that tests whether the control method validates correctly. ItIt isis important important that that you you test test with with multiple multiple numbers, numbers, so so you you get get all all the the cases, cases, and and itit isis It is important that you test with multiple numbers, so you get all the cases, and it is important important that that you you also also test test illegal illegal numbers. numbers. important that you also test illegal numbers.

2.2 METHODS 2.2 METHODS 2.2 METHODS

In Inthe theexplanation explanationof ofclasses classesIIhave havealready alreadydealt dealtwith withmethods, methods,but butthere thereare areaafew fewconcepts concepts In the explanation of classes I have already dealt with methods, but there are a few concepts that that you you should should be be aware aware of. of. As As mentioned, mentioned, aa method method isis identified identified by by its its name name and and the the that you should be aware of. As mentioned, a method is identified by its name and the parameter parameter list. list. The The parameters parameters that that you you specify specify in in the the method method definition, definition, are are called called the the parameter list. The parameters that you specify in the method definition, are called the formal parameters and they defines the values to be transferred to a method. The values that formal parameters and they defines the values to be transferred to a method. The values that formal parameters and they defines the values to be transferred to a method. The values that you youtransfer transferwhen whenthe themethod methodisiscalled, called,isisreferred referredto toasasthe theactual actualparameters. parameters.Above AboveIIhave have you transfer when the method is called, is referred to as the actual parameters. Above I have shown shownhow howto tospecify specifythat thataamethod methodhas hasaavariable variablenumber numberof ofparameters, parameters,which whichisisreally reallyjust just shown how to specify that a method has a variable number of parameters, which is really just aa question question that that the the compiler compiler creates creates an an array array asas the the actual actual parameter. parameter. Methods Methods parameters parameters a question that the compiler creates an array as the actual parameter. Methods parameters can generally be of any type, but you should be aware that primitive types and can generally be of any type, but you should be aware that primitive types and reference reference can generally be of any type, but you should be aware that primitive types and reference types are treated differently. For primitive types the transmitted values are directly types are treated differently. For primitive types the transmitted values are directly copied, copied, types are treated differently. For primitive types the transmitted values are directly copied, and and that that is, is, that that the the stack stack creates creates aa copy copy of of the the parameters parameters and and the the actual actual parameters parameters are are and that is, that the stack creates a copy of the parameters and the actual parameters are copied copied to to these these copies. copies. This This means means that that ifif aa method method isis changing changing the the value value of of aa parameter parameter copied to these copies. This means that if a method is changing the value of a parameter that has a primitive type, then it is the value of the copy on the stack that is changed, that has a primitive type, then it is the value of the copy on the stack that is changed,and and that has a primitive type, then it is the value of the copy on the stack that is changed, and after the method is terminated, then the values of the calling code are unchanged. Wee after the method is terminated, then the values of the calling code are unchanged. Wee after the method is terminated, then the values of the calling code are unchanged. Wee therefore thereforealso alsocall callaaparameter parameterof ofaaprimitive primitivetype typefor foraavalue valueparameter. parameter.IfIfyou youfor forexample example therefore also call a parameter of a primitive type for a value parameter. If you for example consider consider the the following following method method consider the following method public ArrayList getCourses(int year) public ArrayList getCourses(int year)

so isis its its parameter aa primitive primitive type, and and if the method method changes the the value of of year, itit would would so so is its parameter parameter a primitive type, type, and ifif the the method changes changes the value value of year, year, it would only have have effect in in the method, method, but the the change would would not have have effect in in the code code where only only have effect effect in the the method, but but the change change would not not have effect effect in the the code where where the method method was was called. called. the the method was called. Referenceparameters parameters arein in principletransferred transferred inthe the sameway, way, wherethere there onthe the stack Reference Reference parametersare are inprinciple principle transferredin in thesame same way,where where thereon on thestack stack created aa copy copy of of the the parameter parameter and and the the current current value value isis copied copied to to this. this. However, However, you you isis created is created a copy of the parameter and the current value is copied to this. However, you should be be aware of of what isis being being created and and copied. In In the case case of aa reference reference parameter should should be aware aware of what what is being created created and copied. copied. In the the case of of a reference parameter parameter what is created on the stack is a reference, and what is copied is the reference to the current what whatisiscreated createdon onthe thestack stackisisaareference, reference,and andwhat whatisiscopied copiedisisthe thereference referenceto tothe thecurrent current object. As an example the following method has a reference parameter: object. object. As As an an example example the the following following method method has has aa reference reference parameter: parameter: public void add(Course course) throws Exception public void add(Course course) throws Exception

4141 41

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes

If If the the method method creates creates aa new new Course Course object object and and sets sets the the parameter parameter course course to to refer refer to to this this object, object, itit is is still still the the copy copy on on the the stack stack that that change, change, and and the the calling calling code code will will still still refer refer to to the old object. If the method not creates a new Course object it could use the course object’s the old object. If the method not creates a new Course object it could use the course object’s methods methods to to change change the the object’s object’s state, state, as as an an example example itit could could assign assign the the object object aa new new score. score. If If you you do do the the object object that that is is changed changed is is the the object object referenced referenced on on the the stack, stack, that that is is the the same same as as the the object object that that the the calling calling code code refers. refers. The The effect effect of, of, that that aa method method changes changes the the value value of of aa parameter, parameter, is is thus thus different different depending depending on on whether whether itit is is aa reference reference parameter parameter or or value value parameter. parameter. A A good good example example is is aa swap swap method, method, and and thus thus aa method method that that must must reverses reverses the the two two values. values. Consider Consider the the following following method method public static void swap(int a, int b) { int t = a; a = b; b = t; }

Join the best at the Maastricht University School of Business and Economics!

Top master’s programmes • 3  3rd place Financial Times worldwide ranking: MSc International Business • 1st place: MSc International Business • 1st place: MSc Financial Economics • 2nd place: MSc Management of Learning • 2nd place: MSc Economics • 2nd place: MSc Econometrics and Operations Research • 2nd place: MSc Global Supply Chain Management and Change Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012; Financial Times Global Masters in Management ranking 2012

Visit us and find out why we are the best! Master’s Open Day: 22 February 2014

Maastricht University is the best specialist university in the Netherlands (Elsevier)

www.mastersopenday.nl

42 42

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes Classes

which has two parameters that are value types. IfIf the method isis executed as follows: which which has has two two parameters parameters that that are are value value types. types. If the the method method is executed executed as as follows: follows: int[] arr = { 2, 3}; int[] arr = { 2, 3}; swap(arr[0], arr[1]); swap(arr[0], arr[1]); System.out.println(arr[0] + " " + arr[1]); System.out.println(arr[0] + " " + arr[1]);

the last statement prints the the last last statement statement prints prints 2 3 2 3

and the two numbers are not reversed. The first statement creates an array: and the the two two numbers numbers are are not not reversed. reversed. The The first first statement statement creates creates an an array: array: and

When the next statement calls the method swap(), and the variables arr[0] and arr[1] are When the the next next statement statement calls calls the the method method swap(), swap(), and and the the variables variables arr[0] arr[0] and and arr[1] arr[1] are are When transferred as the actual parameters. The method swap() has two parameters and a local transferred as as the the actual actual parameters. parameters. The The method method swap() swap() has has two two parameters parameters and and aa local local transferred variable, and has therefore three fields that are allocated on the stack, and the values of the variable, and and has has therefore therefore three three fields fields that that are are allocated allocated on on the the stack, stack, and and the the values values of of the the variable, actual parameters are copied to this: actual parameters parameters are are copied copied to to this: this: actual

The swap() method works in that copies the value of the parameter to the local variable The swap() swap() method method works works in in that that itit it copies copies the the value value of of the the parameter parameter aaa to to the the local local variable variable The t, and then copy the value of b to a. Finally the value of t is copied to b, and then the and then then copy copy the the value value of of bb to to a. a. Finally Finally the the value value of of tt isis copied copied to to b, b, and and then then the the t,t, and contents of the stack is as shown below. This means that the two values are reversed, but contents of of the the stack stack isis as as shown shown below. below. This This means means that that the the two two values values are are reversed, reversed, but but itit it contents happened on the stack, and after the method is terminated the three elements are removed happened on on the the stack, stack, and and after after the the method method isis terminated terminated the the three three elements elements are are removed removed happened from the stack, and the changes are lost. This means that the array in the calling code from the the stack, stack, and and the the changes changes are are lost. lost. This This means means that that the the array array in in the the calling calling code code from is unchanged. unchanged. isis unchanged.

43 43 43

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes Classes

The The question how, Java write swap() method swap two primitive values, and Thequestion questionisis ishow, how,inin inJava Javatoto towrite writeaaaswap() swap()method methodtoto toswap swaptwo twoprimitive primitivevalues, values,and and itit can not actually be done directly. It is necessary to embed the values in a an object it can can not not actually actually be be done done directly. directly. It It is is necessary necessary to to embed embed the the values values in in aa an an object objectofof of another reference type. One solution would be: another another reference reference type. type. One One solution solution would would be: be: public static static void void swap(int[] swap(int[] a) a) public { { int t t = = a[0]; a[0]; int a[0] = a[1]; a[0] = a[1]; a[1] = = t; t; a[1] } }

Here, theparameter parameterisis isan anarray, array,which whichisis isaaareference referencetype. type.The Thealgorithm algorithmisis isthe thesame, same,and and Here, Here,the the parameter an array, which reference type. The algorithm the same, and clear the method reverses the values a[0] and a[1], but not values on the stack. itit itisis isclear clearthe themethod methodreverses reversesthe thevalues valuesofof ofa[0] a[0]and anda[1], a[1],but butitit itisis isnot notvalues valueson onthe thestack. stack. Consider the following statements where arr is as above: Consider the following statements where arr is as above: Consider the following statements where arr is as above: swap(arr); swap(arr); System.out.println(arr[0] System.out.println(arr[0] + + " " " " + + arr[1]); arr[1]);

If If they they are are performed performed you you get get the the results results If they are performed you get the results 3 32 2 32 and and the the numbers numbers are are therefore therefore reversed. reversed. When When the the method method swap() swap() is is called, called, there there is is this this and the numbers are therefore reversed. When the method swap() is called, there is this time only one value to copy to the stack, which is the reference to the array arr: time only one value to copy to the stack, which is the reference to the array arr: time only one value to copy to the stack, which is the reference to the array arr:

There There is is still still created created aa local local variable, variable, but but when when the the method method is is performed, performed, it it is is the the array array There is still created a local variable, but when the method is performed, it is the array reference on the stack the swap() method works on: reference on the stack the swap() method works on: reference on the stack the swap() method works on:

The The result result of of all all this this is is that that in in practice practice it it may may be be important important to to have have in in mind, mind, where where aa The result of all this is that in practice it may be important to have in mind, where parameter is is aa primitive primitive type type or or aa reference reference type, type, because because reference reference types types can can result result ain in parameter parameter is a primitive type or a reference type, because reference types can result in undesirable undesirable side side effects. effects. undesirable side effects.

44 44 44

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes Classes

Another important thing about reference types that what placed on the stack always Another Another important important thing thing about about reference reference types types isis is that that what what isis is placed placed on on the the stack stack isis is always always a reference. Above I have shown a method that prints a course: aa reference. reference. Above Above II have have shown shown aa method method that that prints prints aa course: course: private private static static void void print(Course print(Course cource) cource) throws throws Exception Exception { { } }

IfIf the method executed If the the method method isis is executed executed print(c1); print(c1);

itit reference to Course object that placed on the stack and not Course object. it isis is aaa reference reference to to aaa Course Course object object that that isis is placed placed on on the the stack stack and and not not aaa Course Course object. object. ItIt It isis is important for a Course object fills much more than a reference. It is thus highly effective important for a Course object fills much more than a reference. It is thus highly effective important for a Course object fills much more than a reference. It is thus highly effective to to transfer objects as parameters to methods. to transfer transfer objects objects as as parameters parameters to to methods. methods.

45 45 45

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

Methods Methodshave havea atype typeororthey theyare arevoid. void.The Thefact factthat thata amethod methodisisvoid voidmeans meansthat thatititdoes does not have a value, and it is therefore not required to have a return statement. As an example not have a value, and it is therefore not required to have a return statement. As an example you youhave havethe themethod methodadd() add()ininthe theclass classStudent. Student.AAvoid voidmethod methodmay maywell wellhave haveananempty empty return statement, which then has the effect that the method is terminated. If a method return statement, which then has the effect that the method is terminated. If a methodhas has a atype, type,ititmust musthave havea areturn returnstatement statementthat thatreturns returnsa avalue valueofofthe thesame sametype typeasasthe themethod’s method’s type. It is important to note that the method can only return one value, but the type. It is important to note that the method can only return one value, but thetype typeofof this thisvalue valueininturn turncan canbebeanything, anything,including includinga aclass classtype typeororananarray. array.As Asananexample, example,the the method returns getCourses() in the class Student return an ArrayList, and precise, method returns getCourses() in the class Student return an ArrayList, and precise, ititisisa areference referencetotosuch suchananobject. object. As Ascan canbebeseen seenfrom fromthe theabove, above,a amethod’s method’sparameters parametersare arecreated createdwhen whenthe themethod methodisis called calledand andinitialized initializedby bythe thecalling callingcode. code.The Theparameters parametersare areremoved removedagain againwhen whenthe the method methodterminates, terminates,and andthey theylive liveonly onlywhile whilethe themethod methodexecutes executesand andthey theycan canonly onlybebe used usedororreferenced referenced from from the the method method itself. itself.Wee Wee say say that that the the parameters parameters scope scope are are the the method’s statements. method’s statements. The Thesame sameapplies appliestotothe thevariables variablesasasa amethod methodmight mightcreate. create.They Theyare arecalled calledlocal localvariables. variables. They are created when the method is called, and removed again when it terminates. They are created when the method is called, and removed again when it terminates.Their Their scope is also limited to the method’s statements. A local variable can be created anywhere scope is also limited to the method’s statements. A local variable can be created anywhereinin the themethod, method,but butthey theyare areallallcreated, created,however howeverwhen whenthe themethod methodisiscalled, called,but butififa avariable variable isisreferenced referencedby bya astatement statementbefore beforeititisisdefined, defined,the thecompiler compilerfails. fails.InInconclusion, conclusion,a amethod method can refer to can refer to 1. 1.instance instancevariables variablesininthe themethods methodsclass class 2. 2.parameters parameters 3. local 3. localvariables variables wherein, wherein,the thelast lasttwo twohave havetheir theirscope scopelimited limitedtotothe themethod methoditself. itself.By Bycontrast, contrast,the thescope scopeofof ananinstance instancevariable variableisislimited limitedtotothe theobject, object,sosothat thatthe thevariable variablelive liveasaslong longasasthe theobject objectdoes. does.

2.3 OBJECTS 2.3 OBJECTS Seen Seenfrom fromthe theprogrammer programmerananapplication applicationconsist consistofofa afamily familyofofclasses, classes,but butfrom fromthe therunning running program it consists of a family of objects that are created on basis of the program’s classes. program it consists of a family of objects that are created on basis of the program’s classes. AAclass classisisa adefinition definitionofofananobject objectininthe theform formofofinstance instancevariables variablesthat thatdefine definewhich whichdata data the theobject objectmust mustconsist consistof, of,asaswell wellasasmethods methodsdefines defineswhat whatone onecan canbebedone donewith withananobject. object. IfIfyou have a class such as Subject, you can define a variable whose type is Subject: you have a class such as Subject, you can define a variable whose type is Subject: Subject s1;

46 46

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes

s1s1isisa avariable variableasasallallthe theother othervariables, variables,but butitithas hasnot not(yet) (yet)a avalue. value.The Thevariable variablecan cancontain contain a areference referencethat thatyou youcan canthink thinkofofasasa apointer pointerthat thatcan canpoint pointtoto(refer (referto) to)ananobject. object.IfIfthe the variable variablenot notrefer refertotoananobject, object,itsitsvalue valueisisnull, null,which whichmerely merelyindicates indicatesthat thatitithas hasno novalue. value. Objects are created with new as follows: Objects are created with new as follows: s1 = new Subject("MAT7", "Matematics 7, Algebra");

That Thatisisnew newfollowed followedby bythe theclass classname nameand anda aparameter parameterlist listthat thatmatches matchesthe theparameters parametersofof a aconstructor. constructor.InInthis thiscase, case,the theclass classhas hasa aconstructor constructorthat thattakes takestwo twoString Stringparameters, parameters,and and ananobject objectcan canbebecreated, created,asasshown shownabove. above.Sometimes Sometimeswee weesay saythat thatthe thestatment statmentinstantiates instantiates ananobject. object.This Thismeans meansthat thatwhen whenthe thevariable variables1s1isisdefined, defined,there thereisisa avariable variablecreated createdon on the thestack: stack:

and andafter afterthe theobject objectisiscreated, created,the thepicture pictureisisthe thefollowing: following:

When Whenananobject objectisiscreated, created,the theclass’s class’sconstructor constructorisisperformed, performed,and andififthere thereare areseveral, several,ititisis the theconstructor constructorwhose whoseparameters parametersmatch matchthe theparameters parameterstransferred transferredwith withnew. new.This Thismeans means that thatthe thespace spaceallocated allocatedtotothe theobject’s object’sinstance instancevariables variablestypical typicalare areinitialized initializedwith withvalues values ininthe theconstructor. constructor.InInfact, fact,the theabove aboveimage imageisisnot notquite quitecorrect, correct,for fora aString Stringisisananobject, object, and andthe thetwo twoinstance instancevariables variablesshould shouldtherefore thereforebebedesigned designedasaspointers pointerstotoString Stringobjects. objects. I Ihave havenot notdone donethat thatpartly partlybecause becausestrings stringsininananapplication applicationininmany manyways waysare areused usedasasifif they theywere wereprimitive primitivevalues, values,and andpartly partlybecause becausethe thedrawing drawingbetter bettermatches matchesthe theway wayyou you think thinkofofa aSubject Subjectobject. object.

4747

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

The object is created on the heap, which is a memory area in which the runtime system can continuously create new objects. When creating an object, the heap manager allocates space for object’s variables, then the constructor is executed. The object then lives as long there is a reference to it, but when it is no longer the case, either because the variable that references the object is removed, or manually is set to null, so the object is removed by the garbage collector, and the memory that the object applied, is released and can be used for new objects. The garbage collector is a program that runs in the background and at intervals remove the objects that no longer have references.

2.4 VISIBILITY Visibility tells where a class or its members may be used. As for classes, it’s simple, when a class is defined either public or else you specify no visibility. A public class can be used anywhere, and any other class can refer to a public class. However, if you do not specify any visibility, the class can only be used by classes in the same package.

Need help with your dissertation? Get in-depth feedback & advice from experts in your topic area. Find out what you can do to improve the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

48

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

Regarding the classes members that can be variables, constructors and methods, there are four possibilities: -----

private public protected no visibility

The meaning of the first two has already been explained and protected is a between thing where a protected member can be referenced from other classes in the same package and from derived classes. I have previously briefly explained inheritance, including derived classes, but the topic is described in more detail in a later chapter in this book, where I will also demonstrate the use of protected. Finally, there is the possibility of not indicating any visibility which means that a member can be referenced only within the same package. It is the programmer of a class that defines visibilty for the class’s members. In principle, one could make everything public, but it would also increase the risk that a variable or method was used in an unintended way. Therefore, you should open as little up for the class’s members as possible. As mentioned earlier, do you usually defines all variables private, and so equips a class with the necessary public methods, and for the sake of derived classes you can also be considered to define methods and exceptionally variables as protected.

2.5 STATICAL MEMBERS Both variables and methods can be static. A static variable is a variable that is shared between all objects of a class. When creating an object of a class on the heap, there is not allocated place for static variables, but they are created somewhere in memory where everyone has access to them, and if they have public visibility, it is not only objects of the class, which have access to them. As an example of using a static variable, the class Student has an id, which is a unique number that identifies a student. When you create objects, it is often necessary that these objects can be identified by a unique key, and to ensure uniqueness, this number is automatically incremented by 1 each time a student is created. It is possible because the class has a static variable that contains the number of the last student created. You must note that it is necessary that this variable is static, since it would otherwise be created each time, you creates a Student object. It is, in this way of identifying objects using an auto-generated number, a technique which is sometimes used in databases. In this context, the solution is a little searched when the number is not saved anywhere and students will then possibly get new numbers the next time the program is excuted, and the purpose is indeed only to show an example of a static variable.

49

JAVA JAVA3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes Classes

There There are are many many other other examples examples of of static static variables, variables, and and as an example example III can can mention mention the the There are many other examples of static variables, and asas an an example can mention the class class Cube Cube from from the the book book Java Java 1, 1, which which had had aaa random random number number generator, generator, which which was was also also class Cube from the book Java 1, which had random number generator, which was also defined definedas staticvariable. variable.There Therewere werethe thereason reasonthat thatall allCube Cubeobjects objectsshould shoulduse usethe thesame same defined asasaaastatic static variable. There were the reason that all Cube objects should use the same random number generator when it is initialized by reading the hardware clock. If each Cube randomnumber numbergenerator generatorwhen whenititisisinitialized initializedby byreading readingthe thehardware hardwareclock. clock.IfIfeach eachCube Cube random object objecthad hadits itsown ownrandom randomnumber numbergenerator, generator,these thesewould wouldpossibly possiblybe beinitialized initializedwith withthe the object had its own random number generator, these would possibly be initialized with the same samevalue, value,thereby therebygenerating generatingthe thesame samesequence sequenceof ofrandom randomnumbers. numbers. same value, thereby generating the same sequence of random numbers. Classes Classes can can also also have have static static methods, methods, and and in in fact fact III have have already already used used many many examples. examples. As As Classes can also have static methods, and in fact have already used many examples. As an anexample examplethe themethod methodstudentOk() studentOk()in inthe theclass classStudent. Student.When Whenaaaclass classhas hasaaastatic staticmethod, method, an example the method studentOk() in the class Student. When class has static method, it can be be used used without without having having an an object object as the method method can can be be referred referred to to with with the the name name itit can can be used without having an object asas the the method can be referred to with the name of ofthe theclass: class: of the class: if (Student.student("[email protected]", (Student.student("[email protected]", "Poul "Poul Klausen") Klausen") if {{ }}

In In general general is static method method written written as other methods, methods, and and can can have have both both parameters parameters In general isis aaa static static method written asas other other methods, and can have both parameters and have a return value, and the same rules apply regarding visibility, but a static and have have aa return return value, value, and and the the same same rules rules apply apply regarding regarding visibility, visibility, but but aa static staticmethod method and method can can not not reference reference instance instance variables variables ––– it not associated associated with with aaa specific specific object. object.You You must must can not reference instance variables itit is isis not not associated with specific object. You must specifically specificallynote notethat thatwithin withinthe theclass classwhere wherethe themethod methodis defined,it canbe bereferenced referencedin in specifically note that within the class where the method isisdefined, defined, ititcan can be referenced in the same way as any other of the class’s methods. the same same way way asas any any other other of of the the class’s class’s methods. methods. the A class may may also also have have aaa static static initialize initialize block block that that can can be be used used to to initialize initialize static static variables, variables, AA class class may also have static initialize block that can be used to initialize static variables, for the following block: forexample examplehas hasthe theclass classStudent Student the the following following block: block: for example has the class Student static static {{ nummer == 1000; 1000; nummer }}

because because by by one one reason reason or or another another II wants wants that that the the first first student student must must have have the the key key 1001. 1001. In In this this case case there there isis no no justification justification for for the the block, block, then then you you asas well well could could initialized initialized the the variable variable directly, directly, but but inin other other contexts contexts itit may may be be important important toto initialize initialize static static variables variables otherwise otherwisethan thanby bysimple simpleassignment, assignment,for forexample exampleby byreading readingthe thedata dataininaafile. file.You Youshould should also alsonote notethat thatthe thesyntax syntaxisissimple, simple,and andthat thataaclass classcan canhave haveall allthe thestatic staticinitialize initializeblocks, blocks, asas you you wish. wish. IfIf there there are are more more the the runtime runtime system system guarantees, guarantees, that that they they are are performed performed inin the theorder orderininwhich whichthey theyappear appearininthe thecode. code.

50 50 50

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes

If you considers a main class, NetBeans creates the following class: package students; public class Students { public static void main(String[] args) { } }

which alone has a method with the name main(). When the program is executed, the runtime system search for a method with this name and where appropriate executes the method. As the runtime system does not create an object of the class Students, the method must be static. If the main() method wants to execute a method in the same class, it must generally be static, and the same applies if you in a static method in the main class refers to the variables in the class:

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge

51 51

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

package students; import java.util.*; public class Students { private static Random rand = new Random(); public static void main(String[] args) { test00(); }

}

private static void test00() { System.out.println(rand.nextDouble()); }

That’s That’s why why II until until this this place place has has always always defined defined members members in in the the main main class class as as static. static. IfIf you you do do not not want want that that –– and and itit isis not not necessary necessary –– you you must must write write something something like like the the following: following: package students; import java.util.*; public class Students { private Random rand = new Random(); public static void main(String[] args) { Students obj = new Students(); obj.test00(); }

}

private void test00() { System.out.println(rand.nextDouble()); }

52 52

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes

This Thismeans meansthat thatininmain() main()method methodcreates createsan anobject objectofofthe theclass classitself, itself,and andusing usingthis thisobject object ititcan canthen thenrefer refertotonon-static non-staticmethods methodsthat thatyou youcan canuse useordinary ordinaryinstance instancevariables. variables.There There are arerarely rarelyany anygood goodreason reasonfor forthis thisstep, step,and andtypically typicallythe themain-class main-classwill willconsists consistsonly onlyofof static staticvariables variablesand andstatic staticmethods. methods.

2.6 2.6 THE THECURRENCYPROGRAM CURRENCYPROGRAM I Iwill willconclude concludethis thischapter chapteron onclasses classeswith withaaprogram programthat thatcan canconvert convertan anamount amountininone one currency currencytotoan anamount amountininanother anothercurrency. currency.The Theprogram programconsists consistsofofseveral severalclasses, classes,but but basically basicallythere thereisisnothing nothingnew newregarding regardingclasses, classes,but butthe theprogram programintroduces introducesthe theconcept conceptofof design designpatterns patternsand andininrespect respectofoftwo twosimple simplepatterns. patterns.AAdesign designpattern patternisisaacertain certainway waytoto solve solvecertain certainproblems problemsthat thatare aregeneral generalininnature natureand andappearing appearingininmany manydifferent differentsituations. situations. ItItisisnatural naturaltotoseek seekaastandard standardfor forhow howtotouse useproven provenmethods methodsfor forsolving solvingsuch suchaaproblem, problem, and andthat’s that’swhat whataadesign designpattern patternis.is.InInthe theexample exampleI Ipresents presentsthe thepatterns patterns 1. 1.aasingleton singleton 2. 2.an aniterator iteratorpattern pattern The Theprogram programhas hasaasimple simplemodel modelclass, class,which whichisiscalled calledCurrency Currencythat thatrepresents representsaacurrency currency with withthree threeproperties: properties: --- currency currencycode code(that (thatisisaacode codeon on33characters) characters) --- currency currencyname name(that (thatmust mustnot notbe beblank) blank) --- currency currencyrate ratethat thatshould shouldbe beaanon-negative non-negativenumber number The Thecode codeofofthe theclass classisisshown shownbelow belowincl. incl.the themost mostimportant importantcomments commentsand anddo donot notrequire require further furtherexplanation: explanation: package currencyprogram; /** * Class that represents a currency when the currency rate is relative to * Danish crowns. */ public class Currency { private String code; // currency code private String name; // currency name private double rate; // currency rate

5353

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

public Currency(String code, String name) throws Exception { this(code, name, 0); } public Currency(String code, String name, double rate) throws Exception { if (!valutaOk(code, name, rate)) throw new Exception("Illegal currency"); this.code = code; this.name = name; this.rate = rate; } public String getCode() { return code; } public String getName() { return name; }

54 54

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

public void setName(String name) throws Exception { if (name == null || name.length() == 0) throw new Exception("Illegal currency name"); this.name = name; } public double getRate() { return rate; } public void setRate(double rate) throws Exception { if (rate < 0) throw new Exception("Illegal currency rate"); this.rate = rate; } public String toString() { return code + ": " + name; }

}

/** * Validates the values of a currency where the code must be three characters, * the name must not be blank and the currency rate must non-negative. * @param code Currency code * @param name Currency name * @param rate Currency rate * @return true, If the three values results in a legal currency, else false. */ public static boolean valutaOk(String code, String name, double rate) { return code != null && code.length() == 3 && name != null && name.length() > 0 && rate >= 0; }

You should note that the above class is a typical model class that describes an object in the You should note that the above class is a typical model class that describes an object in the program’s problem area. program’s problem area.

55 55

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Classes Classes

THE THE SINGLETON SINGLETON PATTERN PATTERN

The The next next class class isis called called CurrencyTable, CurrencyTable, and and isis aa class class that that defines defines the the Currency Currency objects objects that that the the program program knows knows and and has has to to work work with. with. The The program program must must have have an an object object of of the the type type CurrencyTable, CurrencyTable, and and itit isis an an object, object, which which in in principle principle should should always always be be there there and and be be available available no no matter matter where where in in the the program program you you are. are. Since Since itit isis very very often often that that aa situation situation arises arises that that aa program program must must use use an an object object of of aa particular particular type, type, and and you you want want to to ensure ensure 1. 1. the the object object isis always always there, there, without without explicitly explicitly being being created created 2. 2. the the object object isis available available to to all all other other objects objects in in the the program program 3. 3. there there certainly certainly exists exists only only one one object object of of that that type type there there has has been been defined defined aa particular particular design design pattern pattern for for how how the the class class to to such such an an object object should should be be written. written. This This design design pattern pattern isis called called aa singleton. singleton. The The class class can can be be written written as as follows: follows: package currencyprogram; import java.util.*; /** * Class which represents a currency table. The class is implemented as a * singleton. * Data for the currencies is laid out in a table at the end of the code. */ public class CurrencyTable implements Iterable { private static CurrencyTable instance = null; // an instance of the class private ArrayList table = new ArrayList(); // ArrayList to currencies // Private constructor to ensure that the class can not be instantiated // from other classes. private CurrencyTable() { init(); } public static CurrencyTable getInstance() { if (instance == null) { synchronized (CurrencyTable.class) { if (instance == null) instance = new CurrencyTable();

56 56

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Classes Classes

} } return instance;

public Currency getCurrency(String code) throws Exception { for (Currency c : table) if (c.getCode().equals(code)) return c; throw new Exception("Illegal currency"); } public Iterator iterator() { return table.iterator(); } /** * Updating the currency table with a currency. If this currency is already * in the table the name and rate are updated. Otherwise, add a new currency * to the table. * @param currency The currency * @return true, if the table was updated correctly */

57

57

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

public boolean update(Currency currency) { for (Currency c : this) if (c.getCode().equals(currency.getCode())) { try { c.setName(currency.getName()); c.setRate(currency.getRate()); return true; } catch (Exception ex) { return false; } } table.add(currency); return true; } private void init() { for (String line : rates) { StringTokenizer tk = new StringTokenizer(line, ";"); if (tk.countTokens() == 3) { try { String name = tk.nextToken(); String code = tk.nextToken(); double rate = Double.parseDouble(tk.nextToken()); table.add(new Currency(code, name, rate)); } catch (Exception ex) { System.out.println(ex.getMessage() + "\n" + line); } } else System.out.println("Error: " + line); } } private static String[] rates = { "Danske kroner;DKK;100.00", "Euro;EUR;746.00",

58 58

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Classes Classes

"Amerikanske dollar;USD;674.44", "Britiske pund;GBP;1034.10", "Svenske kroner;SEK;79.31", "Norske kroner;NOK;79.68", "Schweiziske franc;CHF;685.66", "Japanske yen;JPY;5.6065", "Australske dollar;AUD;487.61", "Brasilianske real;BRL;171.98", "Bulgarske lev;BGN;381.43", "Canadiske dollar;CAD;510.19", "Filippinske peso;PHP;14.40", "Hongkong dollar;HKD;87.02", "Indiske rupee;INR;10.38", "Indonesiske rupiah;IDR;0.0494", "Israelske shekel;ILS;174.48", "Kinesiske Yuan renminbi;CNY;106.17", "Kroatiske kuna;HRK;97.87", "Malaysiske ringgit;MYR;157.78", "Mexicanske peso;MXN;40.65", "New Zealandske dollar;NZD;458.77", "Polske zloty;PLN;173.82", "Rumænske lei;RON;168.13", "Russiske rubel;RUB;10.42", "Singapore dollar;SGD;483.72", "Sydafrikanske rand;ZAR;49.08", "Sydkoreanske won;KRW;0.5933", "Thailandske baht;THB;19.00", "Tjekkiske koruna;CZK;27.53", "Tyrkiske lira;TRY;231.78", "Ungarske forint;HUF;2.385" };

This This time time there there are are more more details details to to note. note. The The class class has has an an instance instance variable, variable, which which isis called called table and is an ArrayList and should be used for the Currency objects. table and is an ArrayList and should be used for the Currency objects. The The class also has a static variable named instance that is initialized to null. This variable is class also has a static variable named instance that is initialized to null. This variable is an an important part of the singleton pattern. The class has a constructor, but you should note important part of the singleton pattern. The class has a constructor, but you should note that that the the constructor constructor isis defined defined private, private, and and when when the the class class has has no no other other constructors, constructors, itit means means that that other other objects objects can can not not instantiate instantiate objects objects of of this this class. class. It It isis another another important important part of the singleton pattern. part of the singleton pattern. The The ArrayList ArrayList must must be be initialized initialized with with Currency Currency objects, objects, and and itit requires requires currency currency data data in in the the form of a rate list. It can, for example be found on form of a rate list. It can, for example be found on http://www.nationalbanken.dk/da/statistik/valutakurs/Sider/Default.aspx http://www.nationalbanken.dk/da/statistik/valutakurs/Sider/Default.aspx

59 59

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

and an example is laid out in the bottom of the class as an array of strings. The method init() uses this the array to create Currency objects, and the init() method is called from the private constructor. It is of course a little pseudo, since it is not current exchange rates, but if you wants you can update the table. The class has a static method called getInstance(), which returns the static variable instance. It is the last and perhaps most important part of the singleton pattern. The method works in that way that it tests whether the variable instance is null. If so, it creates a CurrencyTable object and assigns the result to instance. It is possible, for the method getInstance() is a member of the class CurrencyTable and can therefore refer to the private constructor. Finally the method returns the variable instance, and thus a reference to a CurrencyTable object. Other objects can refer to the CurrencyTable object by this reference, and when the object can not be created otherwise, there is exactly one object referenced. You should note that the line that instantiates the object is placed in a synchronized block. Preliminary simply accept it, but it is important for programs that creates multiple threads.

Challenge the way we run

EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…

READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM

1349906_A6_4+0.indd 1

22-08-2014 12:56:57

60

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes Classes Classes

THE ITERATOR THE ITERATORPATTERN PATTERN THE THE ITERATOR ITERATOR PATTERN PATTERN

InIn terms the the nothing explain termsofof theother othermethods methodsinin theclass, class,there thereisis nothingtoto explainexcept exceptthe themethod method In In terms terms of of the the other other methods methods in in the the class, class, there there is is nothing nothing to to explain explain except except the the method method iterator(). The class isis an example ofof aaacollection and, inin this case aaacollection ofof Currency iterator(). The class an example collection and, this case collection Currency iterator(). The class is an example of collection and, in this case collection of Currency iterator(). The class is an example of a collection and, in this case a collection of Currency objects. That collections aacertain practice. objects. Thatkind kindofof collectionswith withobjects objectsofof certainkind kindoccur occurvery veryoften ofteninin practice. objects. objects. That That kind kind of of collections collections with with objects objects of of aa certain certain kind kind occur occur very very often often in in practice. practice. One ofof the operations that almost always isis needed isis being able toto iterate over the collection One the operations that almost always needed being able iterate over the collection One of the operations that almost always is needed is being able to iterate over the collection One of the operations that almost always is needed is being able to iterate over the collection with aaloop. the isisoften aapattern with loop.This Thisrequires requiresaccess accesstoto theobjects objectsand anditit oftenresolved resolvedby bymeans meansofof pattern with with aa loop. loop. This This requires requires access access to to the the objects objects and and it it is is often often resolved resolved by by means means of of aa pattern pattern which we call the iterator pattern. The class CurrencyTable implements this pattern asas follows: which we call the iterator pattern. The class CurrencyTable implements this pattern follows: which we call the iterator pattern. The class CurrencyTable implements this pattern as follows: which we call the iterator pattern. The class CurrencyTable implements this pattern as follows: The class called The classimplements implementsan aninterface, interface,which whichhere hereisis calledIterable. Iterable.This Thismeans meansthat that The The class class implements implements an an interface, interface, which which here here is is called called Iterable. Iterable. This This means means that that the class must implements a method with the following signature: the class must implements aa method with the following signature: the class must implements method with the following signature: the class must implements a method with the following signature: public Iterator iterator() public public Iterator Iterator iterator() iterator()

where Iteratorisis aninterface interfacethat thatdefines definesmethods, methods,soso youcan caniterate iterateover overthe the where Iterator an you where where Iterator Iterator is is an an interface interface that that defines defines methods, methods, so so you you can can iterate iterate over over the the collection Currency objects. this case particularly simple, since an ArrayList has collection ofof Currency objects. InIn this case itit isis particularly simple, since an ArrayList has collection of Currency objects. In this case it is particularly simple, since an ArrayList has collection of Currency objects. In this case it is particularly simple, since an ArrayList has such aniterator, iterator,and andthe themethod methodcan cantherefore thereforebe bewritten writtenasas follows: such an follows: such such an an iterator, iterator, and and the the method method can can therefore therefore be be written written as as follows: follows: public Iterator iterator() public public Iterator Iterator iterator() iterator() { { { return table.iterator(); return return table.iterator(); table.iterator(); } } }

How totoeven later, the How evenwrite writean aniterator iteratorI IIwill willreturn returntoto later,but butthe theresult resultofof theiterator iteratorpattern patternisis How How to to even even write write an an iterator iterator I will will return return to to later, later, but but the the result result of of the the iterator iterator pattern pattern is is that you can use the extended for construction: that you can use the extended for construction: that you can use the extended for construction: that you can use the extended for construction: for (Currency c : CurrencyTable.getInstance()) { … } for for (Currency (Currency c c : : CurrencyTable.getInstance()) CurrencyTable.getInstance()) { { … … } }

In reality it is nothing but a short way of writing reality nothing but short way writing InIn Inreality realityitit itisis isnothing nothingbut butaaashort shortway wayofof ofwriting writing for (Iterator itr = CurrencyTable.getInstance().iterator(); for for (Iterator (Iterator itr itr = = CurrencyTable.getInstance().iterator(); CurrencyTable.getInstance().iterator(); itr.hasNext(); ) itr.hasNext(); ) itr.hasNext(); ) { { { Currency c = itr.next(); Currency Currency c c = = itr.next(); itr.next(); … … … } } }

The two classes Currency and CurrencyTable are the program’s model. The two classes Currency and CurrencyTable are the program’s model. Thetwo twoclasses classesCurrency Currencyand andCurrencyTable CurrencyTableare arethe theprogram’s program’smodel. model. The

6161 61 61

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Classes Classes

THE THECONTROLLER CONTROLLER

The Theprogram programhas hasaacontroller controllerclass classthat thatby byusing usingthe theabove abovemodel modelclasses classesmust mustperform performthe the currency currencyconversion, conversion,including includingvalidation validationofofparameters parametersfrom fromthe theuser userinterface: interface: package currencyprogram; import java.util.*; import java.io.*; public class Controller { public double calculate(String amount, Currency from, Currency to) throws Exception { try { return calculate(Double.parseDouble(amount), from, to); } catch (Exception ex) { throw new Exception("Illegal amount"); } } public double calculate(double amount, Currency from, Currency to) throws Exception { if (from == null || to == null) throw new Exception("No currency"); return amount * from.getRate() / to.getRate(); } public ArrayList<String> update(File file) { ArrayList<String> errors = new ArrayList(); try { BufferedReader reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { StringTokenizer tk = new StringTokenizer(line, ";"); if (tk.countTokens() == 3) { try { String name = tk.nextToken(); String code = tk.nextToken(); double rate = Double.parseDouble(tk.nextToken()); CurrencyTable.getInstance().update(new Currency(code, name, rate)); }

6262

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes Classes

catch (Exception ex) { errors.add(line); }

} else errors.add(line);

} reader.close();

}

}

} catch (Exception ex) { errors.add(ex.getMessage()); } return errors;

This e-book is made with

SETASIGN

SetaPDF

PDF components for PHP developers

www.setasign.com 63 63

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

There are two overloadings of the method calculate(), which is the method that will perform the conversion. The difference is only the type of the first parameter, wherein the first converts this from String to a double. Furthermore, there is a method update(), which parameter is a File object. The file will represent a text file that contains a list of currencies when the file must have the same format as the table been laid out in the class CurrencyTable. The method updates the model corresponding to the content of the file. The method returns an ArrayList which contains the lines from the file that could not be successfully parsed into a Currency. MAINCONSOLE

Regarding the program itself it is really two programs. The first is a console application that works as follows: The program starts to print an overview of the current currencies. In turn, there is a loop in which the user for each iteration must 1. Enter the currency code for the currency to be converted from 2. Enter the currency code for the currency to be converted to 3. Enter the amount to be converted and then the program prints the result of the conversion. This dialogue is repeated until the user just types Enter for the first currency code. The program is represented by the class MainConsole. I will not show the code here, but when you study the code, notice how I use that class CurrencyTable is a singleton, and that it implements the iterator pattern. You should note that compared to other console applications that I’ve looked at the code is moved from the main class of its own class. MAINVIEW

The other program is a GUI program that opens the window shown on the next page. To make a currency calculation the user must enter the amount and select two currencies and then click the Calculate button. The view then calls the controller to do the calculation and use the result to update a field with the calculated value. If the user clicks the Clear button, all fields will be cleared, and the combo box’s has no selection. If the user clicks the Update button the program opens a file dialog so the user can browse the file system for a semikolon delimited file with currencies rates. The file is sent to the controller that use the file to update the model’s CurrrenceTable.

64

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

Again, I will not show the code, since it contains nothing new, but the window class is called MainView.

THE DESIGN

The goal of the two versions of the program is to demonstrate why it is important to separate an application in well-defined modules or layers. In this case, the program’s data arre defined by two model classes that is Currency and CurrencyTable, while the data processing is carried out in the class Controller. The difference between the two programs is alone the view layer that in the one case is a console window, while in the second case it is a GUI window. The relationship between the program’s classes can be illustrated as follows, where the arrows shows which classes know who

That is the model layer’s classes do not know neither the controller layer or view layer and the controller layer knows nothing about the view layer. The result is that you can replace the view layer without it affects the rest of the program.

65

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

PROBLEM 2 In the book Java 1 I write a program that could create lottery rows and validates these rows again when the week’s lottery is ready. The program was written as a command where you defines by parameters as arguments on the command line that tells what the command shoul do. You must now write a similar program, but such that the program this time has a graphical user interface. When you opens the program, you should get a simple window where you can choose between the program’s two functions:

www.sylvania.com

We do not reinvent the wheel we reinvent light. Fascinating lighting offers an infinite spectrum of possibilities: Innovative technologies and new markets provide both opportunities and challenges. An environment in which your expertise is in high demand. Enjoy the supportive working atmosphere within our global group and benefit from international career paths. Implement sustainable ideas in close cooperation with other specialists and contribute to influencing our future. Come and join us in reinventing light every day.

Light is OSRAM

66

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

If one here click on the first button, the program should open the following window, that is used to create a new lottery and thus generate new lottery rows:

The lottery rows appears in a list box whose content can then be saved to a file. If you click on the second button, the program shoul open the window below that is used to validate a lottery against the week’s lottery numbers. The window has a text box to enter the week’s lottery numbes and another field to shows the result of a control, and there are two list boxes to the right, which respectively should show the validated rows and possible rows with error.

67

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Classes

You should solve the task by the largest possible extent of reuse of class/code from the solution in Java 1. The class’s LottoNumber, LottoGame and LottoRow should be used as the are. You should write a controller to each of the two windows, and the code for these controller class’s should be found in the class LottoCoupon. After you have written the controller class’s you can remove the class LottoCoupon from the project.

68

Deloitte & Touche LLP and affiliated entities.

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces

3 INTERFACES This chapter describes interfaces and in the next chapter I describes inheritance that is two other object-oriented concepts already briefly mentioned in Java 1, and in fact I has in Java 2 used both concepts without explicitly draw attention to it. An interface defines the properties that a class must have, while inheritance is a question about how to extends a class with new properties in terms of new instance variables or methods. Immediately the two thing do not seems having much to do with each other, but they have largely, and therefore I treated both concepts subsequent. To illustere both concepts I need some examples, and I want to use the same examples as in the previous chapter, namely classes concerning students, and classes concerning books in a library, and much of what follows will also address how these classes can be modified.

360° thinking

.

360° thinking

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers 69

Dis

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

3.1 INTERFACES 3.1 INTERFACES Technically, an interface is a type, and it is a reference type. You can therefore do basically the same with an interface as with a class, except that an interface can not be instantiated. You can not create an object whose type is an interface, but otherwise an interface may be used as a type for parameters, return values and variables. Conceptually, an interface is a contract, and an interface can tell that an object has a specific property. The interface specifies only what you can do with the object, but not how that behavior is implemented, and that’s exactly what you want to achieve. Who that has to use the object, only know it through the defining interface (that is the contract), but do not know anything about how the class that underlies the object is made. So long this class comply with the contract – and does not change the interface – the class can be changed without it affects the code that uses the object. Typically, an interface has only signatures of methods (but there are other options, as explained below). An interface is defined by almost the same syntax as a class, but with the difference that the word class is replaced by the word interface. I will, as mentioned, often use the convention that I let the name of an interface start with a big I. In the previous chapter I defined a the class Subject, representing a teaching subject and thus a concept that can be included in a program concerning education. The concept can be defined as follows (see the project Students3): package students; /** * Defines a subject for an education. */ public interface ISubject { public String getId();

}

/** * @return The subjects name */ public String getName(); /** * Changes the subject's name. The subject must have a name, and if the parameter * does not specify a name the method raises a exception. * @param name The subjects name * @throws Exception If the name is null or blank */ public void setName(String name) throws Exception;

70

JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA JAVA 3: OBJECT-ORIENTED PROGRAMMING

InterFaCes Interfaces InterFaCes

The interface interface isis is called called ISubject, ISubject, and and the the only only thing thing you you can can read read isis is that that aaa concept concept that that isis is aaa The The interface called ISubject, and the only thing you can read that concept that ISubject, has has three three methods methods where where the the comments comments explains explains what what these these methods methods do. do. ISubject, ISubject, has three methods where the comments explains what these methods do. Once you you have have the the interface, interface, aaa class class can can implement implement this this interface: interface: Once Once you have the interface, class can implement this interface: public class class Subject Subject implements implements ISubject ISubject public { {

and itit it isis is the the only only change change in in the the the the class class Subject, Subject, because because the the class class has has (implements) (implements) the the and and the only change in the the class Subject, because the class has (implements) the three methods methods defined defined by by the the interface. interface. So So the the question question isis is what what you you have have achieved achieved with with three three methods defined by the interface. So the question what you have achieved with that and and so so far far nothing, nothing, but but III will will make make some some changes changes in in the the Course Course class. class. ItIt It has has aaa variable variable that that and so far nothing, but will make some changes in the Course class. has variable of the the type type Subject, Subject, and and III will will change change the the definition definition of of this this variable, variable, so so that that itit it instead instead has has of of the type Subject, and will change the definition of this variable, so that instead has the type type ISubject: ISubject: the the type ISubject: private ISubject ISubject subject; subject; private

When aaa class class implements implements an an interface, interface, the the class’s class’s type type isis is special special the the type type of of this this interface, interface, When When class implements an interface, the class’s type special the type of this interface, and therefore therefore itit it makes makes sense sense to to say say that that aaa Subject Subject object object isis is also also an an ISubject. ISubject. III have have also also and and therefore makes sense to say that Subject object also an ISubject. have also changed all all the the parameters parameters of of constructors constructors and and methods methods whose whose type type isis is Subject, Subject, as as their their type type changed changed all the parameters of constructors and methods whose type Subject, as their type now are are ISubject. ISubject. You You should should note note that that the the program program still still can can be be translated translated and and run. run. The The now now are ISubject. You should note that the program still can be translated and run. The result isis is that that the the class class Course Course no no longer longer knows knows the the class class Subject, Subject, but but itit it knows knows only only subject subject result result that the class Course no longer knows the class Subject, but knows only subject objects through through the the defining defining interface interface ISubject. ISubject. AA A Course Course know know what what itit it can can with with aaa subject subject objects objects through the defining interface ISubject. Course know what can with subject (it knows knows the the contract), contract), but but not not how how aaa subject subject isis is implemented. implemented. The The two two classes classes are are now now (it (it knows the contract), but not how subject implemented. The two classes are now more loosely loosely coupled coupled than than they they were were before, before, and and that that means means that that you you get get aaa program program that that more more loosely coupled than they were before, and that means that you get program that is easier easier to to maintain, maintain, as as you you can can change change the the class class Subject Subject without without itit it matters matters for for classes classes that that isis easier to maintain, as you can change the class Subject without matters for classes that use Subject Subject objects. objects. use use Subject objects. The fact fact that that in in this this way way defines defines the the classes classes by by means means of of an an interface, interface, and and other other classes classes The The fact that in this way defines the classes by means of an interface, and other classes only know know aaa class class through through its its interface interface isis is aaa principle principle or or pattern, pattern, commonly commonly referred referred to to as as only only know class through its interface principle or pattern, commonly referred to as programming to to an an interface. interface. programming programming to an interface. An interface interface in in addition addition to to signatures signatures of of methods methods can can also also contain contain static static variables variables and and static static An An interface in addition to signatures of methods can also contain static variables and static methods –– – they they are are not not attached attached to to an an object. object. The The class class Subject Subject has has aaa method method subjectOk(), subjectOk(), methods methods they are not attached to an object. The class Subject has method subjectOk(), which tests tests whether whether the the values values in in aaa subject subject are are legal. legal. ItIt It isis is aaa static static method method and and does does not not depend depend which which tests whether the values in subject are legal. static method and does not depend on aaa Subject Subject object, object, and and itit it can can therefore therefore be be moved moved to to the the interface. interface. This This means, means, however, however, on on Subject object, and can therefore be moved to the interface. This means, however, that in in the the class class Subject, Subject, the the reference reference to to the the method method (there (there are are two) two) must must be be changed changed to to that that in the class Subject, the reference to the method (there are two) must be changed to ISubject.subjectOk(....) ISubject.subjectOk(....)

where you you in in front front of of the the method’s method’s name name has has to to write write name name the the type type that that defines defines the the method. method. where where you in front of the method’s name has to write name the type that defines the method.

71 71 71

JAVA 3: OBJECT-ORIENTED PROGRAMMING

InterFaCes Interfaces

In the same way a Course can be defined by an interface: package students; /** * Defines a course for a specified year for a specific subject. * A course is associated with a particular student, and a course represent * a subject that a student has completed. * It is an assumption that the same subject only can be taking once a year. */ public interface ICourse {

/** * A cource is identified by the subjects id and the year * @return Course ID composed of the year, the subject's id separated by a hyphen */ public String getId(); /** * @return The year where the course is held. */ public int getYear();

We will turn your CV into an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? We will appreciate and reward both your enthusiasm and talent. Send us your CV. You will be surprised where it can take you.

72

Send us your CV on www.employerforlife.com

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

/** * @return true, if the student has completed the course */ public boolean completed(); /** * @return The character that the student has achieved * @throws Exception If a student has not obtained a character */ public int getScore() throws Exception; /** * Assigns this course a score. * @param score The score that is the obtained * @throws Exception If the score is illegal */ public void setScore(int score) throws Exception; /** * Assigns this course a character. * @param score The score that is the obtained * @throws Exception If the score is illegal */ public void setScore(String score) throws Exception; /** * @return Returns the subject for this course */ public ISubject getSubject();

}

/** * Tests whether the parameters for a course are legal * @param year The year for the course * @param subject The subject that this course deals * @return true, If the year is illegal or the subject is null */ public static boolean courseOk(int year, ISubject subject) { return year >= 2000 && year < 2100 && subject != null; }

There is not much to explain, but you should note two things: There is not much to explain, but you should note two things: 1. there is defined a new method getSubject(), which is not part of the class Course 1. there is defined a new method getSubject(), which is not part of the class Course 2. the method toString() is not defined, and it was nor defined in the interface ISubject 2. the method toString() is not defined, and it was nor defined in the interface ISubject

73 73

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Interfaces InterFaCes

The The class class Course Course must must implements implements the the interface interface ICourse, ICourse, and and because because of of the the first first of of the the above above observations, observations, itit isis necessary necessary to to add add aa new new method. method. AA class class that that implements implements an an interface interface must must implement implement all all the the methods methods that that the the interface interface defines. defines. Below Below ii show show the the class class Course Course that now implements the interface ICourse where I have deleted all comments: that now implements the interface ICourse where I have deleted all comments: package students; public class Course implements ICourse { private int year; private ISubject subject; private int score = Integer.MIN_VALUE; public Course(int year, ISubject subject) throws Exception { if (!ICourse.courseOk(year, subject)) throw new Exception("Illegal course"); this.year = year; this.subject = subject; } public Course(int year, String id, String name) throws Exception { subject = new Subject(id, name); if (!ICourse.courseOk(year, subject)) throw new Exception("Illegal year"); this.year = year; } public String getId() { return year + "-" + subject.getId(); } public int getYear() { return year; } public ISubject getSubject() { return subject; }

74 74

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

public boolean completed() { return score > Integer.MIN_VALUE; } public int getScore() throws Exception { if (score == Integer.MIN_VALUE) throw new Exception("The student has not completed the course"); return score; } public void setScore(int score) throws Exception { if (!scoreOk(score)) throw new Exception("Illegal ckaracter"); this.score = score; } public void setScore(String score) throws Exception { try { int number = Integer.parseInt(score);

AXA Global Graduate Program Find out more and apply

75 75

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes InterFaCes

if if (!scoreOk(number)) (!scoreOk(number)) throw throw new new Exception("Illegal Exception("Illegal score"); score"); this.score = number; this.score = number;

} }

} }

} } catch catch (Exception (Exception ex) ex) { { throw throw new new Exception("Illegal Exception("Illegal score"); score"); } }

public public String String toString() toString() { { return return subject.toString(); subject.toString(); } } private private boolean boolean scoreOk(int scoreOk(int score) score) { { return return true; true; } }

You You should should note: note: ---------

implements implements and and then then the the syntax syntax to to implements implements an an interface interface there is added a new method getSubject() that returns there is added a new method getSubject() that returns aa ISubject ISubject that the method courseOk() is removed and moved to the that the method courseOk() is removed and moved to the interface interface that the reference to courseOk() in the constructor is changed that the reference to courseOk() in the constructor is changed

After After these these changes, changes, the the program program can can be be translated translated and and run. run. If If you you have have to to complies complies with with the the principle principle of of programming programming to to an an interface, interface, the the class class Student Student must be altered so that all instances of the type Course are changed to ICourse, but must be altered so that all instances of the type Course are changed to ICourse, but then then the class Student is also decoupled from the class Course and know only a course by the class Student is also decoupled from the class Course and know only a course by the the defining interface ICourse. defining interface ICourse. An An interface interface can can in in the the same same way way as as aa class class be be public public or or it it can can be be specified specified without without visibility. visibility. In the latter case, the interface is known only within the package to which it belongs. In the latter case, the interface is known only within the package to which it belongs. In In the above examples, everywhere I have defined methods in an interface as public, but they the above examples, everywhere I have defined methods in an interface as public, but they are are by by default, default, even even ifif you you do do not not write write it. it. II prefer prefer always always to to write write the the word word public, public, as as it it clarifies the methods visibility. If an interface defines data (contains variables and see possibly clarifies the methods visibility. If an interface defines data (contains variables and see possibly the the interface interface IPoint) IPoint) these these are are always always public public static static final final

76 76 76

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Interfaces InterFaCes

JAVA 3: OBJECT-ORIENTED PROGRAMMING

InterFaCes

whether whether you you write write itit or or not. not. Again, Again, II prefer prefer to to write write itit all, all, thus thus clarifying clarifying that that itit isis aa whether you write it or not. Again, I prefer to write it all, thus clarifying that it is a public public constantly. constantly. public constantly. II would would then then add add aa small small change change to to the the class class Student. Student. The The class class has has aa static static method method studentOk(), studentOk(), I would then add a small change to the class Student. The class has a static method studentOk(), which isis legal. which validates validates the the name name and and email email address address of of aa student student to to test test where where aa student student legal. which validates the name and email address of a student to test where a student is legal. The for The controls controls are are quite quite trivial, trivial, since since the the method method only only tests tests whether whether the the value value isis specified specified for The controls areand quite trivial, sincenow theextend methodthe only tests whether the value specified for both the address. II will control, so also whether both the name name and address. will now extend the control, so the the method method alsoistests tests whether both the address name I will now extend the control, so the method also tests whether the in the format: the mail mail addressand in address. the correct correct format: the mail address in the correct format: public static boolean studentOk(String mail, String name) { public static boolean studentOk(String mail, String name) { return mailOk(mail) && name != null && name.length() > 0; } return mailOk(mail) && name != null && name.length() > 0; }

private static boolean mailOk(String mail) { private static boolean mailOk(String mail) { if (mail == null || mail.length() == 0) return false; String if (mail pattern == null = || mail.length() == 0) return false; "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3} String pattern = \\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3} Pattern p = Pattern.compile(pattern); \\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; Matcher p m = Pattern.compile(pattern); p.matcher(mail); Pattern return m.matches(); Matcher m = p.matcher(mail); } return m.matches(); }

Here, the method mailOk() is a method to validate whether a string may be a mail address. Here, the method mailOk() isis aa method to whether aa string may aa mail Here, the at method mailOk() method to validate validate whether string may be be mail address. address. You must this place just accept that method does, but it happens by using a so-called regular You must at this place just accept that method does, but it happens by using a so-called regular You must at this place just accept that method does, but it happens by using a so-called expressions, as discussed later in Java 4. You should note that the method is private,regular since expressions, as discussed later in Java 4. You should note that the method is private, since expressions, as an discussed 4. You should that the private, since the control of address later is notina Java natural property of note a student. It ismethod thus a is helper method. the control of an address is not a natural property of a student. It is thus a helper method. the control of an address is not a natural property of a student. It is thus a helper method. I’ve also changed the method setMail(): I’ve I’ve also also changed changed the the method method setMail(): setMail(): public void setMail(String mail) throws Exception { public void setMail(String mail) throws Exception { if (!studentOk(mail, navn)) throw new Exception("Illegal mail address"); this.mail if (!studentOk(mail, = mail; navn)) throw new Exception("Illegal mail address"); } this.mail = mail; }

Note that I here directly could have used mailOk(), but for the sake of the next I have not. Note that that II here here directly directly could could have have used used mailOk(), mailOk(), but but for for the the sake sake of of the the next next II have have not. not. Note

77 77 77

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Interfaces InterFaCes

Also aa student student can can be be defined defined by by an an interface interface IStudent, IStudent, but but II will will not not show show the the entire entire code code Also here here since since it it does does not not contain contain anything anything new. new. However, However, there there is is one one thing thing which which creates creates aa challenge. challenge. II want want to to move move the the method method studentOk() studentOk() to to the the interface, interface, and and since since it it is is aa static static method, you can immediately do it, but the private method maikOk() should be moved method, you can immediately do it, but the private method maikOk() should be moved to, and and it it gives gives aa problem to, problem since since an an interface interface can can not not have have aa private private method. method. An An interface interface may may have have an an inner inner class, class, and and although although it it is is aa subject subject which which first first addressed addressed later, it’s just a question that there is a class within an interface. The method studentOk() later, it’s just a question that there is a class within an interface. The method studentOk() can thus thus be be moved moved to to the the interface interface as as follows: follows: can package students; import java.util.*; import java.util.regex.*; /** * The interface defines a student when a student is characterized by an * identifier, a name and a mail address. * A student also has a list of courses that the student has completed or * participate in. */

I joined MITAS because I wanted real responsibili� I joined MITAS because I wanted real responsibili�

Real work International Internationa al opportunities �ree wo work or placements

78 78

�e Graduate Programme for Engineers and Geoscientists

Maersk.com/Mitas www.discovermitas.com

�e G for Engine

Ma

Month 16 I was a construction Mo supervisor ina const I was the North Sea super advising and the No he helping foremen advis ssolve problems Real work he helping fo International Internationa al opportunities �ree wo work or placements ssolve pr

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes InterFaCes

public interface IStudent public interface IStudent { { … … /** /** * Tester om mail og navn kan repræsentere en studerende. * Tester om mail og navn kan repræsentere en studerende. * @param mail En studerendes mailadresse * @param mail En studerendes mailadresse * @param navn En studerendes navn * @param navn En studerendes navn * @return true, hvis mail og navn repræsenterer en lovlig studerende * @return true, hvis mail og navn repræsenterer en lovlig studerende */ */ public static boolean studentOk(String mail, String navn) public static boolean studentOk(String mail, String navn) { { return Email.mailOk(mail) && navn != null && navn.length() > 0; return Email.mailOk(mail) && navn != null && navn.length() > 0; } }

} }

class Email class Email { { private static boolean mailOk(String mail) private static boolean mailOk(String mail) { { String pattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9] String pattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9] {1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; {1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; Pattern p = Pattern.compile(pattern); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(mail); Matcher m = p.matcher(mail); return m.matches(); return m.matches(); } } } }

Theimportant importantofofthis thisexample exampleisistotoshow showthat thatan aninterface interfacecan canhave havean aninner innerclass. class. The The important of this example is to show that an interface can have an inner class. Classes can can implement implement an an interface, interface, which which asas stated stated corresponds corresponds toto the the class class comply comply aa Classes Classes can implement an interface, which as stated corresponds to the class comply a contract.Classes, Classes,however, however,can canimplements implementsmultiple multipleinterfaces interfacesand andthus thuscomply complywith withseveral several contract. contract. Classes, however, can implements multiple interfaces and thus comply with several contracts.IfIfthe theclass classimplements implementsseveral severalinterfaces interfacesthe thesyntax syntaxisistotolist listthem themasasaacomma comma contracts. contracts. If the class implements several interfaces the syntax is to list them as a comma separated list list after after the the word word implements. implements. As As an an example, example, the the following following interface interface defines defines separated separated list after the word implements. As an example, the following interface defines pointsininthe theECTS ECTSsystem: system: points points in the ECTS system: package students; package students; /** /** * Defines how many ECTS assigned to a subject. * Defines how many ECTS assigned to a subject. */ */ public interface IPoint public interface IPoint { {

/** /** * Number of points a year * Number of points a year */ */ public static final int AAR = 60; public static final int AAR = 60;

7979 79

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA

Interfaces InterFaCes InterFaCes

/** /** @return The The subject's subject's ECTS ECTS ** @return */ */ public int getECTS(); getECTS(); public int /** /** Changes the the subtect's subtect's ECTS ECTS ** Changes * @param ects The subject's ECTS * @param ects The subject's ECTS @throws Exception Exception The The number number must must not not be be negative negative ** @throws */ */ public void void setECTS(int setECTS(int ects) ects) throws throws Exception; Exception; public } }

The The interface interface is not particularly particularly interesting, interesting, as as it only in in principle principle defines defines an an integer, integer, but but The interface isis not not particularly interesting, as itit only only in principle defines an integer, but you you might might assume assume that that aaa subject subject must must have have attached attached an an ECTS, ECTS, and and the the class class Subjects Subjects could could you might assume that subject must have attached an ECTS, and the class Subjects could then then be be written written as as follows follows (where (where III again again has has removed removed all all comments): comments): then be written as follows (where again has removed all comments): package students; students; package public class class Subject Subject implements implements ISubject, ISubject, IPoint IPoint public { { private String String id; id; // the the subject subject id id private // private String name; // the subject's name private String name; // the subject's name private int int ects ects == 0; 0; // // the the subtect's subtect's ECTS ECTS private public Subject(String Subject(String id, id, String String name) name) throws throws Exception Exception public {{ this(id, name, name, 0); 0); this(id, }} public Subject(String Subject(String id, id, String String name, name, int int ects) ects) throws throws Exception Exception public { { if (!ISubject.subjectOk(id, (!ISubject.subjectOk(id, name)) name)) if throw new Exception("The subject must have have both both an an ID ID and and aa name"); name"); throw new Exception("The subject must if (ects (ects << 0) 0) throw throw new new Exception("ECTS Exception("ECTS must must be be non-negative"); non-negative"); if this.id = id; this.id = id; this.name == name; name; this.name this.ects = ects; this.ects = ects; }} public String String getId() getId() public {{ return id; id; return }}

80 80 80

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

public String getName() { return name; } public void setName(String name) throws Exception { if (!ISubject.subjectOk(id, name)) throw new Exception("The subject must have a name"); this.name = name; } public int getECTS() { return ects; } public void setECTS(int ects) throws Exception { if (ects < 0) throw new Exception("ECTS must be non-negative"); this.ects = ects; }

93%

OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS FOLLOWING GRADUATION

MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE

5 Specializations

Personalize your program

www.ie.edu/master-management

#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES

[email protected]

81 81

Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Interfaces InterFaCes

public String toString() { return name; }

The Theclass classnow nowimplements implementstwo twointerfaces, interfaces,and andmust musttherefore thereforeimplement implementthe thetwo twomethods, methods, the new interface defines. Also, I have expanded the class with a new constructor. You the new interface defines. Also, I have expanded the class with a new constructor. Youshould should note the use of this where til old constructor calls the new constructor. You should note the use of this where til old constructor calls the new constructor. You shouldnote, note, that thatafter afterthe theclass classSubject Subjectisischanged changedthe theprogram programcan canstill stillbebetranslated translatedand andexecuted. executed.AA Subject Subjectobject objectstill stillhas hasthe thetype typeISubject, ISubject,but butititalso alsohas hasthe thetype typeIPoint, IPoint,but butititisisnot notused. used.

EXERCISE EXERCISE44 Start Startby bycreating creatinga acopy copyofofthe theproject projectLibrary3 Library3and andcall callthe thecopy copyfor forLibrary4. Library4.Open Openthe the copy in NetBeans. copy in NetBeans. For Foreach eachofofthe thethree threeclasses classesPublisher, Publisher,Author Authorand andBook, Book,you youmust mustwrite writeananinterface, interface,and and the respective classes must implement the interfaces. Note also that it means that the method the respective classes must implement the interfaces. Note also that it means that the method isbnOk() isbnOk()should shouldbebemoved movedtotothe theinterface interfaceIBook. IBook.After Afterthe thethree threeclasses classesare aredefined definedusing using interfaces, interfaces,and andyou youmust mustmodify modifythe theclasses classescode, code,sosothe thethree threeclasses classesisisasasloosely looselycoupled coupled asaspossible, and you should change the main class for something like the following: possible, and you should change the main class for something like the following: public static void main(String[] args) { try { IBook b1 = create("978-1-59059-855-9", "Beginning Fedora From Noice to Professional", 2007, 1, 519, new Publisher(123, "Apress"), new Author("Shashank", "Sharma"), new Author("Keir", "Thomas")); IBook b2 = new Book("978-87-400-1676-5", "Spansk Vin"); print(b1); print(b2); b2.setReleased(2014); b2.setEdition(1); b2.setPages(335); b2.setPublisher(new Publisher(200, "Politikkens Forlag")); b2.getAuthors().add(new Author("Thomas", "Rydberg")); print(b2); } catch (Exception ex) { System.out.println(ex.getMessage()); } }

82 82

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

private static void print(IAuthor a) { … } private static void print(IBook book) { … } private static IBook create(String isbn, String title, int released, int edition, int pages, IPublisher publisher, IAuthor … authors) throws Exception { … }

3.2 MORE MORE STUDENTS STUDENTS 3.2 Above, II have have introduced introduced interfaces interfaces that that defines defines the the properties properties of of an an existing existing class, class, but but in in Above, practice, you you usually usually go go the the other other way way and and defines defines an an interface interface that that defines defines aa concept concept in in the the practice, program area area of of concern, concern, and and then then you you (or (or let let others others do do it) it) can can write write aa class class that that implements implements program that interface. interface. Above, Above, II have have introduced introduced definitions definitions of of students students and and courses courses in in the the form form of of that IStudent and and ICourse ICourse and and then then itit might might be be natural natural to to define define aa team team of of students, students, where where the the IStudent team must must have have aa name name and and otherwise otherwise isis simply simply aa collection collection of of students: students: team package students; import java.util.*; /** * Interface, that defines a team of students. */ public interface ITeam extends Iterable { /** * @return Name of the team */ public String getName(); /** * Add students to the team * @param stud The students to be added */ public void add(IStudent … stud); /** * Remove a student from the team. * @param id Id on the student to be removed * @return true, if the student was found and removed */ public boolean remove(int id);

83 83

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

/** * Returns a student with a paticular id. * @param id The id for the student to be returned * @return The student identified by id * @throws Exception If the student is not found */ public IStudent getStudent(int id) throws Exception; /** * Returns all students, where the name contains the value of the parameter. * @param navn The search value * @return All students where the name contains the search value */ public ArrayList findStudents(String name);

}

/** * Returns all students, that has completed in a particular course a year. * @param id Id of the subject * @param aar Year * @return All students who matches the search values */ public ArrayList findStudents(String id, int year);

84 84

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Interfaces InterFaCes

There Thereisisnot notmuch muchtotosay sayabout aboutthe theinterface interfacewhen whenthe thecomments commentsexplaining explainingthe themeaning meaning ofofeach eachmethod, method,but butyou youshould shouldnote notethat thatan aninterface interfacecan caninherit inheritanother anotherinterface, interface,and and ininthis thiscase casethe theinterface interfaceITeam ITeaminherits inheritsthe theinterface interfaceIterable<Student>. Iterable<Student>.This Thismeans meansthat thataa class classthat thatimplements implementsthe theinterface, interface,also alsohas hastotoimplement implementthe theiterator iteratorpattern. pattern.Below Belowisisaa class classthat thatimplements implementsthe theinterface interfaceITeam: ITeam: package students; import java.util.*; public class Team implements ITeam { private String name; // the name private ArrayList list = new ArrayList(); // the students public Team(String name) { this.name = name; } public Iterator iterator() { return list.iterator(); } public String getName() { return name; } public void add(IStudent … stud) { for (IStudent s : stud) list.add(s); } public boolean remove(int id) { for (int i = 0; i < list.size(); ++i) if (list.get(i).getId() == id) { list.remove(i); return true; } return false; }

8585

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes InterFaCes

public IStudent getStudent(int id) throws Exception public IStudent getStudent(int id) throws Exception { { for (IStudent s : list) if (s.getId() == id) return s; for (IStudent s : list) if (s.getId() == id) return s; throw new Exception("Student not found"); throw new Exception("Student not found"); } } public ArrayList findStudents(String name) public ArrayList findStudents(String name) { { ArrayList lst = new ArrayList(); ArrayList lst = new ArrayList(); for (IStudent s : list) if (s.getName().contains(name)) lst.add(s); for (IStudent s : list) if (s.getName().contains(name)) lst.add(s); return lst; return lst; } }

} }

public ArrayList findStudents(String id, int year) public ArrayList findStudents(String id, int year) { { ArrayList lst = new ArrayList(); ArrayList lst = new ArrayList(); for (IStudent s : list) for (ICourse c : s.getCourses(year)) for (IStudent s : list) for (ICourse c : s.getCourses(year)) if (c.completed() && c.getSubject().getId().equals(id)) lst.add(s); if (c.completed() && c.getSubject().getId().equals(id)) lst.add(s); return lst; return lst; } }

There There is is not not much much to to explain, explain, but but you you should should note note that that the the class class implements implements the the iterator iterator pattern, and that the class does not know the class Student, but only know a student through pattern, and that the class does not know the class Student, but only know a student through the the interface interface IStudent. IStudent. As As the the last last concept concept in in this this family family of of types types regarding regarding students students and and education education II will will look look at at an an institution, but this time I will not define an interface. The class should instead be written institution, but this time I will not define an interface. The class should instead be written as as aa singleton, singleton, and and the the program program therefore therefore needs needs to to know know the the actual actual class, class, why why aa defining defining interface is not quite as interesting. The class is called Institution: interface is not quite as interesting. The class is called Institution: package students; package students; import java.util.*; import java.util.*; public class Institution implements Iterable public class Institution implements Iterable { { private static Institution instance = null; private static Institution instance = null; public final static String NAVN = "The Linux University"; public final static String NAVN = "The Linux University"; private ArrayList list = new ArrayList(); private ArrayList list = new ArrayList(); private Institution() private Institution() { { } }

86 86 86

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

public static Institution getInstance() { if (instance == null) { synchronized (Institution.class) { if (instance == null) instance = new Institution(); } } return instance; } public ITeam getTeam(String name) throws Exception { for (ITeam t : list) if (t.getName().equals(name)) return t; throw new Exception("There is no team with the name " + name); } public void add(ITeam … teams) { for (ITeam t : teams) list.add(t); }

Excellent Economics and Business programmes at:

“The perfect start of a successful, international career.” CLICK HERE

to discover why both socially and academically the University of Groningen is one of the best places for a student to be

www.rug.nl/feb/education

87 87

JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

InterFaCes Interfaces InterFaCes InterFaCes

public Iterator iterator() public Iterator iterator() { public Iterator iterator() { return list.iterator(); { list.iterator(); } return return list.iterator(); }} } } }

The class class isislargely largelyself-explanatory, self-explanatory,but butyou you must note is written a singleton, The must note thatthat it isitwritten as a as singleton, and The class is largely self-explanatory, but you must note that it is written as a singleton, and the pattern is implemented in exactly the same way as I have shown in the currency Thepattern class isis largely self-explanatory, butsame you way must it is as a converter. singleton, the implemented in exactly the as Inote havethat shown in written the currency and the pattern is implemented in exactly the same way as I have shown in the currency converter. Alsothe note that the classinimplements iterator pattern and notein finally that the and the isclass implemented exactly the the same way I have shown the currency Also notepattern that implements the iterator pattern andas note finally that the class knows converter. Also note that the class implements the iterator pattern and note finally that the class the knows only thethat other classes there defining interfaces. converter. Also note theprogram class implements the iterator pattern and note finally that the only other program classes through therethrough defining interfaces. class knows only the other program classes through there defining interfaces. class knows only the other program classes through there defining interfaces. Finally, II shows shows the the test test program. program. The The main main class class already already has has aa print() print() method, method, which which prints prints Finally, Finally, I shows the test program. The main class already has a print() method, which prints an IStudent. IStudent. have added the following following method to print printhas an aInstitution: Institution: Finally, I shows the added test program. The main class already print() method, which prints an II have the method to an an IStudent. I have added the following method to print an Institution: an IStudent. I have added the following method to print an Institution: private static void print() private static void print() { private static void print() { try { try { try { System.out.println(Institution.NAME); { System.out.println(Institution.NAME); System.out.println(); System.out.println(Institution.NAME); System.out.println(); for (ITeam team : Institution.getInstance()) System.out.println(); for (ITeam team : Institution.getInstance()) { for (ITeam team : Institution.getInstance()) { System.out.println(team.getName()); { System.out.println(team.getName()); for (IStudent stud : team) System.out.println(team.getName()); for (IStudent stud : team) { for (IStudent stud : team) { System.out.println(); { System.out.println(); print(stud); System.out.println(); } print(stud); print(stud); } System.out.println(); } } System.out.println(); System.out.println(); }} } } catch (Exception ex) } catch (Exception ex) { catch (Exception ex) { System.out.println(ex.getMessage()); { } System.out.println(ex.getMessage()); System.out.println(ex.getMessage()); }} } } You should note that both print() methods not dependents }

on the specific classes. The You should note that both print() methods not dependents on the specific classes. The main() method as follows: You should should noteis that that both print() print() methods methods not not dependents dependents on on the the specific specific classes. classes. The The You note both main() method is as follows: main() method method isis as as follows: follows: main() public static void main(String[] args) public static void main(String[] args) { public static void main(String[] args) { Institution.getInstance().add( { Institution.getInstance().add( createTeam("Team-A 2015", Institution.getInstance().add( createTeam("Team-A 2015", createStudent("[email protected]", "Olga Jensen", createTeam("Team-A 2015", createStudent("[email protected]", "OlgatoJensen", createCourse(2015, "PRG", "Introduction Java", 5, 7), createStudent("[email protected]", "Olga Jensen", createCourse(2015, "PRG", "Introduction to Java", 5, 7), createCourse(2015, "PRG", "Introduction to Java", 5, 7),

88 88 88 88

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

InterFaCes Interfaces InterFaCes

createCourse(2015, "OPS", "Operating Systems", 15, 2), createCourse(2015, "SYS", "System Development", 5, 2) createCourse(2015, "OPS", "Operating Systems", 15, 2), ), createCourse(2015, "SYS", "System Development", 5, 2) createStudent("[email protected]", "Harald Andersen", ), createCourse(2015, "PRG", "Introduction to Java", 5, 4), createStudent("[email protected]", "Harald Andersen", createCourse(2015, "NET", "Computer Networks", 10, 12) createCourse(2015, "PRG", "Introduction to Java", 5, 4), ) createCourse(2015, "NET", "Computer Networks", 10, 12) ), ) createTeam("Team-B 2015", ), createStudent("[email protected]", "Svend Hansen", createTeam("Team-B 2015", createCourse(2015, "OPS", "Operating Systems", 15, 10), createStudent("[email protected]", "Svend Hansen", createCourse(2015, "RRG", "Introduction to Java", 5, 0), createCourse(2015, "OPS", "Operating Systems", 15, 10), createCourse(2015, "DBS", "Database Systems", 20, 7) createCourse(2015, "RRG", "Introduction to Java", 5, 0), ), createCourse(2015, "DBS", "Database Systems", 20, 7) createStudent("[email protected]", "Svend Frederiksen", ), createCourse(2015, "OPS", "Operationg Systems", 15, 2), createStudent("[email protected]", "Svend Frederiksen", createCourse(2015, "NETL", "Computer Networks", 10, 10) createCourse(2015, "OPS", "Operationg Systems", 15, 2), ) createCourse(2015, "NETL", "Computer Networks", 10, 10) ) ) ); ) print(); ); } print(); }

adding two teams to the institution where each team has two students. Finally the method adding two teams to the institution where each team has two students. Finally the method prints Theinstitution method uses some to create Finally objects:the method addingthe twoinstitution. teams to the where eachhelper team methods has two students. prints the institution. The method uses some helper methods to create objects: prints the institution. The method uses some helper methods to create objects: private static ITeam createTeam(String name, IStudent … studs) { private static ITeam createTeam(String name, IStudent … studs) ITeam team = new Team(name); { team.add(studs); ITeam team = new Team(name); return team; team.add(studs); } return team; } private static IStudent createStudent(String mail, String name, ICourse … course) { private static IStudent createStudent(String mail, String name, ICourse … course) try { { try return new Student(mail, name, course); { } return new Student(mail, name, course); catch (Exception ex) } { catch (Exception ex) return null; { } return null; } } private static ICourse createCourse(int year, String id, String name, int ects, } int score) private static ICourse createCourse(int year, String id, String name, int ects, { int score) {

89 89 89

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

InterFaCes Interfaces InterFaCes

try { try { ICourse course = new Course(year, id, name); course.setScore(score); ICourse course = new Course(year, id, name); ((IPoint)course.getSubject()).setECTS(ects); course.setScore(score); return course; ((IPoint)course.getSubject()).setECTS(ects); } return course; catch (Exception ex) } { catch (Exception ex) { return null; } return null; }} }

If you run the program you get the following result: If you run the program you get the following result: If you run the program you get the following result: The Linux University The Linux University Team-A 2015 Team-A 2015

[1001] Olga Jensen Introduction to Java, Score: 7 [1001] Olga Jensen Operating Systems, Score: 2 7 Introduction to Java, Score: System Development, Score: 22 Operating Systems, Score: System Development, Score: 2

American online LIGS University is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and ▶▶ save up to 16% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!

Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.

90 90 90

JAVA 3: OBJECT-ORIENTED PROGRAMMING

InterFaCes

[1002] Harald Andersen JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces

Introduction to Java, Score: 4 JAVA 3: OBJECT-ORIENTED PROGRAMMING Computer Networks, Score: 12 Team-B 2015 [1002] Harald Andersen Introduction to Java, Score: 4 [1003] Svend Hansen Computer Networks, Score: 12 Operating Systems, Score: 10 Team-B 2015 Introduction to Java, Score: 0 Database Systems, Score: 7 [1003] Svend Hansen Operating Systems, Score: 10 [1004] Svend Frederiksen Introduction to Java, Score: 0 Operationg Systems, Score: 2 Database Systems, Score: 7 Computer Networks, Score: 10

InterFaCes

[1004] Svend Frederiksen Score: 2 Computer Networks, Score: 10 Make a copy of the project Library4

EXERCISE 5 Operationg Systems,

and call the copy Library5. Open the copy in NetBeans. You must write an interface defining a book list:

EXERCISE 5

package library;

Make a copy of the project Library4 and call the copy Library5. Open the copy in NetBeans. You must write an interface defining a book list:

import java.util.*;

package library; /** * Defines a book list import java.util.*; */ public interface IBooklist extends Iterable {/** * Defines a book list /** */ * Method, that adds books to the book list. public interface IBooklist extends Iterable * If the list already contains a book with { the same ISBN, the book should be /** * ignored. Method,books that The addsbooks bookstotobethe book list. ** @param added * If the list already contains a book with */ the samevoid ISBN, the book… should public add(IBook books);be * ignored. * @param books The books to be added /** */ * Method that creates a book and adds it to the list. The book is created on the public void add(IBook … books); * basis of et variabelt antal strenge, som fortolkes på følgende måde i den * nævnte rækkefølge: /** * ISBN ** Method title that creates a book and adds it to the list. The book is created on the of year et variabelt antal strenge, som fortolkes på følgende måde i den ** basis release * nævnte rækkefølge: * edition ISBN ** pages * title * release year * edition * pages 91

91 91

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

* publisher name * an number of pairs of authors' first and last name * Only the first two arguments are required. * Publisher's number extracted from the ISBN (see problem 1). * @param elem Values to the book * @throws Exception If the passed values are not legal book data */ public void add(String … elem) throws Exception; /** * Return the book with a certain isbn. * @param isbn ISBN of the book to be returned * @return The book idenfificeret of isbn * @throws Exception If the book is not found */ public IBook getBog(String isbn) throws Exception;

}

/** * Search books in the book list and returns a list of the books that matches the * search values. * The list is searched combined so that a book matching the search values if it * matches all search values. * If a String is null or blank, the criterion is ignored. The same applies to an * int that is 0. * By searching on strings that should not be distinction between uppercase and * lowercase letters, and a criterion matches if the book value contains the * search string. * Especially by searching the author a book match if it has a single author, * whose first and last name contains the values searched. * @param isbn The book's ISBN, which matches the book if it is null, blank or * the book's ISBN contains the value * @param title The book's title, which matches the book if it is null, blank or * book title contains the value * @param year The book's publication, matching the book if 0 or release year is * equal to the value * @param edition The book's edition that matches the book if 0 or the book's * edition is equal to the value * @param publisher The name of the publisher, which matches the book if it is * null, blank or publisher's name contains the value * @param firstname Matches if null, blank or the book has an author whose first * name contains the value * @param lastname Matches if null, blank or the book has an author whose last * name contains the value * @return All books that matches the search values */ public ArrayList find(String isbn, String title, int year, int edition, String publisher, String firstname, String lastname);

92 92

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Write Write aa class class Booklist Booklist that that implements implements the the must writes a test method. You can define must writes a test method. You can define contains data for for 10 10 books: books: contains data

InterFaCes Interfaces

interface. interface. When When you you have have written written the the class, class, you you the following array in the main program, which the following array in the main program, which

private static String[][] data = { { "978-1-59059-855-9", "Beginning Fedora From Novice to Professional", "2007", "1", "519", "Apress", "Shashank", "Sharma", "Keir", "Thomas" }, { "978-0-13-275727-0", "A practical guide to Fedora and Red Hat Enterprise Linux", "2011", "6", "519", "Prentice Hall", "Mark G.", "Sobell" }, { "978-1-4842-0067-4", "Beginning Fedora Desktop: Fedora 20 Edition", "2014", "1", "459", "Apress", "Richard", "Petersen" }, { "978-0-470-48504-0", "Fedora 11 and Red Hat Enterprise Linux Bible", "2011", "1", "1076", "Wiley Publishing", "Christopher", "Negus", "Eric", "Foster-Johnson" }, { "978-1-118-99987-5", "Linux Bible", "2015", "9", "859", "John Wiley & Sons", "Christopher", "Negus" }, { "0-534-95054-X", "Understanding Data Coomunications & Networks", "1999", "2", "711", "Cole Publishing", "William A.", "Shay" }, { "978-0-13-255317-9", "Computer Networks", "2011", "5", "952", "Prentice Hall", "Andrew S.", "Tanenbaum", "David J.", "Wetherall" }, { "0-13-148521-0", "Structured Computer Organization", "2006", "5", "777", "Prentice Hall", "Andrew S.", "Tanenbaum" },

93 93

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

{ "978-0-321-54622-7", "Data Structures & Problem Solving Using Java", "2010", "4", "1011", "Addison-Wesley", "Mark Allen", "Weiss" }, { "978-0-321-63700-0", "LINQ To Objects Using C# 4.0", "2010", "1", "312", "Addison-Wesley", "Troy", "Magennis" }, };

Next, Next,write writeaatest testmethod methodon onthe thebasis basisofofthese thesedata datathat thatcreates createsaabook booklist listwith with10 10books books and andprint printthe thebooks bookswhose whosetitle titlecontains containsthe theword wordFedora. Fedora.

3.3 FACTORIES 3.3 FACTORIES The Theprogram programStudents Studentsnow nowconsists consistsofofclasses classeswhere wherethe thecoupling couplingbetween betweenthe theclasses classesare are defined definedby byinterfaces. interfaces.None Noneofofthe theclasses classesknow knowabout aboutthe theother otherclasses classesexistence, existence,including including how howthese theseclasses classesare areimplemented, implemented,but butthey theyknow knowwhat whatyou youcan cando dowith withobjects objectsofofthe the specific specificclasses, classes,since sincethey theyknow knowthe thecontracts. contracts.Software Softwareconsists consistsofofmodules modules(which (whichhere herecan can be betranslated translatedinto intoclasses), classes),and andititisisaagoal goaltotowrite writesoftware softwarethat thatconsists consistsofofasasloosely looselycoupled coupled modules modulesasaspossible. possible.To Toprogram programtotoan aninterface interfaceisisan animportant importantstep stepininthat thatdirection, direction,but but somewhere, somewhere,the thespecific specificobjects objectsmust mustbe becreated, created,and andininthe theabove abovetest testprogram programisisdone done ininthe theparticular particularhelp helpmethods. methods.However, However,ititisisalso alsothe theonly onlyplace placewhere wheretotoreferences referencesthe the concrete concreteclasses. classes. You Youcan canmove movethe thecode codethat thatcreates createsthe theobjects objectstotoaaspecial specialclass, class,which whichisiscalled calledaafactory factory class class(a(aclass classwhich whichproduces producesobjects). objects).I’ve I’veadded addedthe thefollowing followingclass classtotothe theprogram: program: package students; public abstract class Factory { public static ISubject createSubject(String id, String name) throws Exception { return new Subject(id, name); } public static ISubject createSubject(String id, String name, int ects) throws Exception { return new Subject(id, name); } public static ICourse createCourse(int year, ISubject subject) throws Exception { return new Course(year, subject); }

94 94

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

public static ICourse createCourse(int year, String id, String name) throws Exception { return new Course(year, createSubject(id, name)); } public static IStudent createStudent(String mail, String name, ICourse … course) throws Exception { return new Student(mail, name, course); }

}

public static ITeam createTeam(String name, IStudent … studs) { ITeam team = new Team(name); team.add(studs); return team; }

The class consists only of static methods that creates objects of a concrete type, but returns the objects as an interface types. The class is defined abstract, and this means that the class can not be instantiated. With the class Factory available, the test program can be written as follows, where I have not shown the printing methods, as they are not changed: public static void main(String[] args) { try { Institution.getInstance().add( Factory.createTeam("Team-A 2015", Factory.createStudent("[email protected]", "Olga Jensen", createCourse(2015, "PRG", "Introduction to Java", 5, 7), createCourse(2015, "OPS", "Operating Systems", 15, 2), createCourse(2015, "SYS", "System Development", 5, 2) ), Factory.createStudent("[email protected]", "Harald Andersen", createCourse(2015, "PRG", "Introduction to Java", 5, 4), createCourse(2015, "NET", "Computer Networks", 10, 12) ) ), Factory.createTeam("Team-B 2015", Factory.createStudent("[email protected]", "Svend Hansen",

95 95

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Interfaces InterFaCes

createCourse(2015, "OPS", "Operating Systems", 15, 10), createCourse(2015, "RRG", "Introduction to Java", 5, 0), createCourse(2015, "DBS", "Database Systems", 20, 7) ), Factory.createStudent("[email protected]", "Svend Frederiksen", createCourse(2015, "OPS", "Operationg Systems", 15, 2), createCourse(2015, "NETL", "Computer Networks", 10, 10) )

) ); print();

}

} catch (Exception ex) { System.out.println(ex); }

private static ICourse createCourse(int year, String id, String name, int ects, int score) throws Exception {

.

96 96

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Interfaces InterFaCes

ICourse course = Factory.createCourse(year, Factory.createSubject(id, name, ects)); course.setScore(score); return course;

Then there are no coupling between the program and the concrete classes. In this case, the class Factory is trivial with simple methods that do nothing but to encapsulate a new operation, but other factory classes may be more complex, for example, to read data from a file or database.

EXERCISE 6 Create a copy of the project Library5 and call the copy Library6. Open the copy in NetBeans and create the following factory class: public class Factory { public static IPublisher createPublisher(int nummer, String name) throws Exception { … } public static IAuthor createAuthor(String firstname, String lastname) throws Exception { … } public static IBook createBook(String … elem) throws Exception { … }

}

public static IBooklist createBooklist() { … }

Here are three of the methods trivial, but the method that creates a book is relatively Here are three of the methods trivial, but the method that creates a book is relatively complex. You can get the most of the required code from the class Booklist. complex. You can get the most of the required code from the class Booklist. After writing the class, change the main program, so all objects in the class Library are After writing the class, change the main program, so all objects in the class Library are created by calls to the Factory class. You must also change the class Booklist, so that it also created by calls to the Factory class. You must also change the class Booklist, so that it also applies the Factory class. applies the Factory class.

97 97

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance InherItanCe

4 INHERITANCE 4 INHERITANCE If you have a class and you want another class, similar to the first, but expanded with new variables or methods, or you may want one or more methods to work in a different way, the new class can inherit the first. As explained in Java 1, the class that inherits, is called for a derived class, while the class it is inherited from is called the base class. Other words for the same are respectively subclasses and superclass. I will in this section illustrate inheritance through classes, which represent loans in a bank. To make it simple, I will assume that a loan is characterized by the formation expenses and an amount that I together will call the loan’s principal, an interest rate which I would assume is constant throughout the loan period, and a number of periods, which is the number of payments to repay the loan. It thus corresponds to the same requirements as I assumed in the loan calculation program in the book Java 2. Under these conditions a loan is defined as the following class: package loanprogram; public class Loan { private double principal; // the amount borrowed inc. costs private double interestRate; // interest rate as a number between 0 and 1 private int periods; // the number of periods or number of payments public Loan(double principal, double interestRate, int periods) { this.principal = principal; this.interestRate = interestRate; this.periods = periods; } public double getPrincipal() { return principal; } public double getInterestRate() { return interestRate; } public int getPeriods() { return periods; }

98

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance InherItanCe

public double repayment(int n) { return 0; } public double interest(int n) { return 0; } public double payment(int n) { return 0; }

}

public double outstanding(int n) { return 0; }

Join the best at the Maastricht University School of Business and Economics!

Top master’s programmes • 3  3rd place Financial Times worldwide ranking: MSc International Business • 1st place: MSc International Business • 1st place: MSc Financial Economics • 2nd place: MSc Management of Learning • 2nd place: MSc Economics • 2nd place: MSc Econometrics and Operations Research • 2nd place: MSc Global Supply Chain Management and Change Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012; Financial Times Global Masters in Management ranking 2012

Visit us and find out why we are the best! Master’s Open Day: 22 February 2014

Maastricht University is the best specialist university in the Netherlands (Elsevier)

www.mastersopenday.nl

99 99

{{ { {

return return 0; 0;

0; return 0; JAVA 3: PROGRAMMING JAVAreturn 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING }} } }

Inheritance InherItanCe

public double outstanding(int public double double outstanding(int outstanding(int n) n) public public double outstanding(int n) The first methods should self-explanatory, The first three three methods should be ben) self-explanatory, and and the the last last four four returns returns {{ { { }} } }

return 0; return 0; 0; return return 0;

1. 1. repaid repaid by by the the payment payment of of the the nth nth payment payment 2. 2. interest interest by by the the payment payment of of the the nth nth payment payment 3. the payment 3.three the nte nte payment The first methods should be self-explanatory, and the last four returns Thefirst first three methods shouldbe beself-explanatory, self-explanatory,and andthe thelast lastfour fourreturns returns The The first three three methods methods should should be self-explanatory, and the last four returns 4. 4. the the remaining remaining debt debt immediately immediately after after the the payment payment of of the the nth nth payment payment }} } }

1. repaid by the payment of the nth payment 1. repaid repaidby bythe thepayment paymentof ofthe thenth nthpayment payment 1. 1. repaid by the payment of the nth payment

2. interest by the payment of the nth payment 2. interest interest by thelast payment of thenth nthpayment payment IfIf you look at the four methods, they you look atby the last fourof methods, they are are all all trivial trivial and and returns returns all all 0. 0. AA loan loan can can be be 2. 2. interest by the the payment payment of the the nth payment 3. the nte payment 3. in theseveral ntepayment payment repaid ways, repaid in several ways, and and to to write write the the code code for for the the last last four four methods, methods, itit requires requires that that you you 3. 3. the the nte nte payment 4. the remaining debt immediately after the payment of the nth payment 4. the remaining debt immediately after the payment of the nth payment know itit isis for aa kind loan question. That the class know what fordebt kind loan in in after question. That know know thepayment class Loan Loan not, not, and and therefore therefore 4. 4. what the theremaining remaining debt immediately immediately after the the payment payment of of the the nth nth payment itit isis not not able able to to implement implement these these methods methods in in aa meaningful meaningful way. way. ItIt may may on on the the other other hand hand If you look at the last four methods, they are all trivial and returns all 0. A loan can be repaid in If you look at the last four methods, they are all trivial and returns all 0. A loan can be repaid in If If you look look at at the last last four fourclass. methods, methods, they they are are all all trivial trivial and and returns returns all all 0. 0. A A loan loan can can be be repaid repaid in in be possible in aa derived beyou possible inthe derived class.

several ways, and to write the code for the last four methods, requires that you know what is for severalways, ways,and andto towrite writethe thecode codefor forthe thelast lastfour fourmethods, methods,ititititrequires requiresthat thatyou youknow knowwhat whatititititis isfor foraaaa several several ways, and to write the code for the last four methods, requires that you know what is for kind loan in question. That know the class Loan not, and therefore is not able to implement these kind loan loan in in question. question. That That know know the the class class Loan Loan not, not, and and therefore therefore itititit is is not not able able to to implement implement these these kind kind loan in question. That know the class Loan not, and therefore is not able to implement these The most common loan is an annuity that is characterized by the fact that you for each The most common loan is an annuity that is characterized by the fact that you for each methods in meaningful way. ItIt may on the other hand be possible in derived class. methodsin inaaaameaningful meaningfulway. way.It Itmay mayon onthe theother otherhand handbe bepossible possiblein inaaaaderived derivedclass. class. methods methods in meaningful way. may on the other hand be possible in derived class.

payment payment pays pays the the same same every every time. time. When When you you all all the the time time have have to to pay pay interest interest on on what what is ititloan means that the relationship between the repayment and the interest are is outstanding, outstanding, means that the that relationship between thefact repayment and thepayment interestpays are The most common loan is an annuity that is characterized by the fact that you for each payment pays The mostcommon common loan isan an annuity that ischaracterized characterized bythe the fact thatyou youfor for each payment pays The The most most common loan is is an annuity annuity that is is characterized by by the fact that that you for each each payment pays the same every time. When you all the time have to pay interest on what is outstanding, means that the sameevery every time.When When youall allperiod. thetime timeIf have to pay interest on what isoutstanding, outstanding, means that changed throughout the bb isisto the size of loan (the loan rr isisthat the changed throughout the repaid repaid period. If the size of the theon loan (the loan principal), principal), the the the same same every time. time. When you you all the the time have have to pay pay interest interest on what what is is outstanding, ititititmeans means that the relationship between the repayment and the interest are changed throughout the repaid period. If the relationship between the repayment and the interest are changed throughout the repaid period. If interest rate periode and of periods, the payment can be interest rate each each periode and nn isis the the number ofare periods, the paymentthe can be determined determined the the relationship relationship between between the the repayment repayment and andnumber the the interest interest are changed changed throughout throughout the repaid repaid period. period. IfIf bbbb is the size of the loan (the loan principal), is the interest rate each periode and is the number of is the size size of the loan loanformula: (the loan loan principal), principal), rrrr is is the the interest interest rate rate each each periode periode and and nnnn is is the the number number of of is is the the size of the the loan (the (the loan principal), is the interest rate each periode and is the number of using the following using theof following formula: periods, the payment can be determined using the following formula: periods,the thepayment paymentcan canbe bedetermined determinedusing usingthe thefollowing followingformula: formula: periods, periods, the payment can be determined using the following formula:

𝑏𝑏𝑏𝑏 𝑏𝑏𝑏𝑏𝑏𝑏𝑏𝑏 𝑏𝑏𝑏𝑏 𝑏𝑏𝑏𝑏𝑏𝑏𝑏𝑏 𝑦𝑦 = 𝑦𝑦𝑦𝑦 = 𝑦𝑦𝑦𝑦𝑦𝑦 = = 11− −𝑛𝑛 −𝑛𝑛𝑛𝑛 (1 (1+ + 𝑟𝑟) −(1 +𝑟𝑟) 𝑏𝑏𝑏𝑏)−𝑛𝑛 −𝑛𝑛𝑛𝑛 (1 11− − + 𝑏𝑏𝑏𝑏)

The outstanding debt after you have paid the kth be using the Theoutstanding outstanding debt after you have paid thepayment kthpayment payment can becalculated calculated using theformula formula The debt after you have paid the kth can be calculated using the formula The outstanding debt after you have paid thekth kth payment canbe becan calculated usingthe the formula The outstanding debt after you have paid the payment can calculated using formula The outstanding debt after you have paid the kth payment can be calculated using the formula (1 (1+ + 𝑟𝑟) − +𝑟𝑟) 𝑏𝑏𝑏𝑏)𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘− −1111 (1 (1 + 𝑏𝑏𝑏𝑏) − 𝑘𝑘𝑘𝑘𝑘𝑘 𝑘𝑘𝑘𝑘𝑘𝑘 − 𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟 = 𝑏𝑏(1 + 𝑟𝑟) 𝑦𝑦 𝑏𝑏𝑏𝑏𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟 = 𝑏𝑏𝑏𝑏(1 + 𝑏𝑏𝑏𝑏) − 𝑦𝑦𝑦𝑦 𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟 𝑏𝑏𝑏𝑏𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟 = = 𝑏𝑏(1 𝑏𝑏𝑏𝑏(1+ +𝑟𝑟) 𝑏𝑏𝑏𝑏) − −𝑦𝑦𝑦𝑦𝑦𝑦 𝑟𝑟𝑟𝑟𝑏𝑏𝑏𝑏𝑏𝑏𝑏𝑏

So isisthe kind of loan that looked at in Java 2. Soititititis thekind kindof ofloan loanthat thatIIIIlooked lookedat atin inJava Java2. 2. So So the kind of loan that looked at in Java So the kind of that II looked at in So ititisisisthe the kind of loan loan that looked at 2. in Java Java 2. 2.

will now write class that represents an annuity when the class will inherit the class Loan: willnow nowwrite writeaaaaclass classthat thatrepresents representsan anannuity annuitywhen whenthe theclass classwill willinherit inheritthe theclass classLoan: Loan: IIIIwill will now write class that represents an annuity when the class will inherit the class Loan:

II will will now now write write aa class class that that represents represents an an annuity annuity when when the the class class will will inherit inherit the the class class Loan: Loan:

package loanprogram; package loanprogram; loanprogram; package package loanprogram;

package loanprogram;

public class Annuity extends Loan public class class Annuity Annuity extends extends Loan Loan public public class Annuity extends Loan { { {{ public Annuity principal, extends Loan public Annuity(double double interestRate, int periods) publicclass Annuity(double principal, double interestRate, interestRate, int int periods) periods) public Annuity(double principal, double public Annuity(double principal, double interestRate, int periods) { {{ {{ super(principal, interestRate, periods); super(principal, interestRate, periods); public Annuity(double principal, double interestRate, int periods) super(principal, interestRate, periods); super(principal, interestRate, periods); } } { }}

super(principal, interestRate, periods);

public double payment(int n) public double double payment(int payment(int n) n) public public double payment(int n) } { { {{

68 68 68 68

100 100

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Inheritance InherItanCe InherItanCe

public public double double payment(int payment(int n) n) { { return return getPrincipal() getPrincipal() * * getInterestRate() / (1 getInterestRate() / (1 – – Math.pow(1 Math.pow(1 + + getInterestRate(), getInterestRate(), -getPeriods())); -getPeriods())); } } public public double double outstanding(int outstanding(int n) n) { { return return getPrincipal() getPrincipal() * * Math.pow(1 Math.pow(1 + + getInterestRate(), getInterestRate(), n) n) – – payment(0) * (Math.pow(1 + getInterestRate(), n) – 1) / getInterestRate(); payment(0) * (Math.pow(1 + getInterestRate(), n) – 1) / getInterestRate(); } } public public double double interest(int interest(int { { return return outstanding(n outstanding(n – – 1) 1) } }

} }

n) n) * * getInterestRate(); getInterestRate();

public public double double repayment(int repayment(int n) n) { { return return payment(n) payment(n) – – interest(n); interest(n); } }

You should should note note that that the the class class inherits inherits Loan, Loan, and and how how to to specify specify that that with with extends. extends. The The class class You consists only only of of aa constructor constructor and and the the four four methods methods which which should should work work in in aa different different way. way. consists Wee say say that that the the class class overrides overrides the the four four methods methods from from the the base base class. class. That That the the class class inherits inherits Wee means it it beyond beyond what what it it itself itself defines defines also also can can use use public public variables variables and and methods methods from from the the means base class. class. Because Because aa derived derived class class can can only only refer refer to to what what in in the the base base class class is is defined defined as as public, public, base it can can therefore therefore not not reference reference the the base base class’s class’s variables, variables, but but it it must must use use to to the the get-methods. get-methods. it When creating creating an an annuity annuity object, object, the the instance instance variables variables must must be be initialized, initialized, but but they they When are in in the the base base class, class, and and are are initialized initialized using using the the base base class’s class’s constructor. constructor. It It is is therefore therefore are necessary in in one one way way or or another another to to get get this this constructor constructor performed. performed. It It must must be be called called from from necessary the constructor constructor of of the the class class Annuity, Annuity, but but since since you you can can not not directly directly call call aa constructor, constructor, it it is is the necessary with with aa special special syntax: syntax: necessary super(principal, super(principal, interestRate, interestRate, periods); periods);

that calls calls the the base base class’s class’s constructor. constructor. The The statement statement super super must, must, be be the the first first statement statement in in that the derived derived class’s class’s constructor. constructor. the

101 101 101

JAVA JAVA3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Inheritance InherItanCe

The The biggest biggest challenge challenge in in writing writing the the class class Annuity Annuity isis to to implement implement the the above above formulas. formulas. Here Here you you must must notice notice the the method method Math.pow(), Math.pow(), which which calculates calculates the the power power of of an an argument. argument. With With this method available, it is quite simple to write the code to the four calculation methods. this method available, it is quite simple to write the code to the four calculation methods. IfIf you you have have an an object object of of the the type type Annuity: Annuity: Annuity loan = new Annuity(10000, 0.015, 10);

then then you you can can write write aa statement statement like like the the following: following: System.out.println(loan.repayment(5));

and and the the method method isis repayment() repayment() in in the the class class Annuity Annuity isis performed. performed. You You can can also also write write System.out.println(laan.getPrincipal());

as loan loan isis an an Annuity Annuity that that inherits inherits Loan Loan and and method method getPrincipal() getPrincipal() isis available. available. as

102 102

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Inheritance InherItanCe

Sometimes Sometimes itit can can be be conveniently conveniently directly directly to to refer refer to to the the variables variables in in the the base base class class from from aa method method in in aa derived derived class, class, but but without without making making them them public. public. This This isis possible possible ifif the the variables variables are are defined defined protected: protected: public class Loan { protected double principal; // the amount borrowed inc. costs protected double interestRate; // interest rate as a number between 0 and 1 protected int periods; // the number of periods

A A protected protected variable variable can can not not be be referenced referenced outside outside the the class’s class’s package package (it (it has has package package visibility), visibility), but but itit can can be be referenced referenced from from derived derived classes classes –– even even ifif they they belong belong to to aa different different package. package. As an example the class Annuity now can be written as follows: As an example the class Annuity now can be written as follows: package loanprogram; public class Annuity extends Loan { public Annuity(double principal, double interestRate, int periods) { super(principal, interestRate, periods); } public double payment(int n) { return principal * interestRate / (1 – Math.pow(1 + interestRate, -periods)); } public double outstanding(int n) { return principal * Math.pow(1 + interestRate, n) – payment(0) * (Math.pow(1 + interestRate, n) – 1) / interestRate; } public double interest(int n) { return outstanding(n – 1) * interestRate; }

}

public double repayment(int n) { return payment(n) – interest(n); }

103 103

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Inheritance InherItanCe

InInthis thiscontext, context,there thereare areno nobig bigdifferences, differences,but butininother othersituations situationsititmay maybebenecessary necessarytoto open openup upthe theprotection, protection,sosoderived derivedclasses classescan canreference referencevariables variablesininthe thebase baseclass. class. Note Notethat thatthe themethods methodsalso alsocan canbebeprotected. protected. An Anamortization amortizationisisa atable tableshowing showinga asummary summaryofofthe thepayments paymentsofofa aloan loanand andfor foreach each payment shows the payment, repayment, interest and outstanding debt. The following class payment shows the payment, repayment, interest and outstanding debt. The following class represents representsananamortization: amortization: package loanprogram; public class Amortization { private Loan loan; public Amortization(Loan loan) { this.loan = loan; }

}

public void print() { System.out.println( "==================================================================="); System.out.printf("Principal: %12.2f\n", loan.getPrincipal()); System.out.printf("Interest rate: %12.2f %%\n", loan.getInterestRate() * 100); System.out.printf("Number of periods: %12d\n\n", loan.getPeriods()); System.out.println( "Periods Payment Repayment Interest Outstanding"); System.out.println( "----------------------------------------------------------------------"); for (int n = 1; n <= loan.getPeriods(); ++n) System.out.printf("%7d%16.2f%17.2f%15.2f%15.2f\n", n, loan.payment(n), loan.repayment(n), loan.interest(n), loan.outstanding(n)); System.out.println( "----------------------------------------------------------------------"); }

Thereisisnot notmuch muchtotoexplain, explain,but butnote notethat thatthe theparameter parametertotothe theconstructor constructorhas hasthe thetype type There Loanand andthe theclass classAmortization Amortizationthus thusisisnot notaware awareofofthe thespecific specificloan loantypes typessuch suchasasAnnuity. Annuity. Loan willreturn returntotothat thatshortly. shortly. I Iwill

104 104

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Inheritance InherItanCe

With With the the class class Amortisation Amortisation available, available, you you can can perform perform the the following following program: program: public static void main(String[] args) { new Amortization(new Annuity(10000, 0.015, 10)).print(); }

and and the the result result isis asas shown shown below: below: =================================================================== Principal: 10000,00 Interest rate: 1,50 % Number of periods: 10 Periods Payment Repayment Interest Outstanding ---------------------------------------------------------------------1 1084,34 934,34 150,00 9065,66 2 1084,34 948,36 135,98 8117,30 3 1084,34 962,58 121,76 7154,72 4 1084,34 977,02 107,32 6177,70 5 1084,34 991,68 92,67 5186,02 6 1084,34 1006,55 77,79 4179,47 7 1084,34 1021,65 62,69 3157,82

Need help with your dissertation? Get in-depth feedback & advice from experts in your topic area. Find out what you can do to improve the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

105 105

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance InherItanCe InherItanCe

8 1084,34 1036,97 47,37 2120,85 8 1084,34 1036,97 47,37 2120,85 9 1084,34 1052,53 31,81 1068,32 9 1084,34 1052,53 31,81 1068,32 10 1084,34 1068,32 16,02 0,00 10 1084,34 1068,32 16,02 0,00 -------------------------------------------------------------------------------------------------------------------------------------------

In addition to the result, note that it is the methods in the class Annuity that are performed In addition to the result, note that it is the methods in the class Annuity that are performed and it is not obvious. The class Amortization only know the type of Loan that have trivial and it is not obvious. The class Amortization only know the type of Loan that have trivial methods, all of which returns 0. Nevertheless, it is the methods of the class Annuity that methods, all of which returns 0. Nevertheless, it is the methods of the class Annuity that are executed, and it is, even if the class Amortization only know the type Loan. When such are executed, and it is, even if the class Amortization only know the type Loan. When such it is the runtime system that remembers that the object loan actually has the type Annuity it is the runtime system that remembers that the object loan actually has the type Annuity and uses therefore the object with the right methods. It is one of the key concepts of objectand uses therefore the object with the right methods. It is one of the key concepts of objectoriented programming and is called polymorphism. oriented programming and is called polymorphism. If you considers the class Loan, then, as mentioned above the four calculation methods are If you considers the class Loan, then, as mentioned above the four calculation methods are trivial and all simply returns 0. These methods are somehow meaningless, and it makes no trivial and all simply returns 0. These methods are somehow meaningless, and it makes no sense to create objects whose type is Loan. If you did that, and sent such an object over sense to create objects whose type is Loan. If you did that, and sent such an object over a Amortization object, you would get an amortization table, where all numbers are 0. The a Amortization object, you would get an amortization table, where all numbers are 0. The problem can be solved by making the four methods abstract: problem can be solved by making the four methods abstract: package loanprogram; package loanprogram; public abstract class Loan public abstract class Loan { { protected double principal; protected double double interestRate; principal; protected protected double interestRate; protected int periods; protected int periods;

// // // // // //

the amount borrowed inc. the amount borrowed inc. interest rate as a number interest rate as a number the number of periods the number of periods

costs costs 0 and 1 between between 0 and 1

public Loan(double principal, double interestRate, int periods) public Loan(double principal, double interestRate, int periods) { { this.principal = principal; this.principal = principal; this.interestRate = interestRate; this.interestRate = interestRate; this.periods = periods; } this.periods = periods; } public double getPrincipal() public double getPrincipal() { { return principal; } return principal; } public double getInterestRate() public double getInterestRate() { { return interestRate; } return interestRate; }

106 106 106

JAVA JAVA3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance InherItanCe InherItanCe InherItanCe

public int int getPeriods() getPeriods() public public int getPeriods() { { { return periods; return return periods; periods; } } } public abstract double double repayment(int n); n); public public abstract abstract double repayment(int repayment(int n); public abstract double double interest(int n); n); public public abstract abstract double interest(int interest(int n); public abstract double double payment(int n); n); public public abstract abstract double payment(int payment(int n); public abstract double double outstanding(int n); n); public public abstract abstract double outstanding(int outstanding(int n); } } }

An abstract abstract method method isis just just a prototype prototype or or a signature signature for for a method method in in the the same same way way as as An An abstract method is just aa prototype or aa signature for aa method in the same way as you defines defines methods methods in in an an interface. interface. When When aa class class contains contains abstract abstract methods, methods, the the class class isis you you defines methods in an interface. When a class contains abstract methods, the class is abstract, and and itit must must be be declared declared as as an an abstract abstract class: class: abstract, abstract, and it must be declared as an abstract class: public abstract class class Loan public public abstract abstract class Loan Loan

An abstract class class can not not be instantiated, instantiated, and you you can not not with new new create an an object whose whose An An abstract abstract class can can not be be instantiated, and and you can can not with with new create create an object object whose type is Loan Loan but an an abstract class class can easily easily be parameter parameter to aa method. method. That class class Loan has has type type is is Loan but but an abstract abstract class can can easily be be parameter to to a method. That That class Loan Loan has four abstract methods methods means that that anyone who who knows anything anything that isis aa Loan Loan knows that that four four abstract abstract methods means means that anyone anyone who knows knows anything that that is a Loan knows knows that the object in in question, has has the four four methods that that the abstract abstract class specify. specify. the the object object in question, question, has the the four methods methods that the the abstract class class specify. If the class class Loan isis changed changed to an an abstract class class as shown shown above, the the program can can still be be If If the the class Loan Loan is changed to to an abstract abstract class as as shown above, above, the program program can still still be translated and run, run, and itit gives gives the same same result. translated translated and and run, and and it gives the the same result. result. One way way to to think think of of abstract abstract classes classes isis that that you you have have to to write write aa class class Loan Loan and and know know what what One One One way way to to think think of of abstract abstract classes classes is is that that you you have have to to write write aa class class Loan Loan and and know know what what properties and and methods methods aa Loan Loan must must have, have, but but some some of of the the methods methods you you are are not not able able properties properties properties and and methods methods aa Loan Loan must must have, have, but but some some of of the the methods methods you you are are not not able able to implement, implement, because because you you do do not not have have sufficient sufficient knowledge. knowledge. These These methods methods can can then then to to to implement, implement, because because you you do do not not have have sufficient sufficient knowledge. knowledge. These These methods methods can can then then defined abstract abstract and and postpone postpone implementation implementation to to the the specific specific derived derived classes classes who who have have the the defined defined defined abstract abstract and and postpone postpone implementation implementation to to the the specific specific derived derived classes classes who who have have the the necessary knowledge. knowledge. necessary necessary necessary knowledge. knowledge. III will will write write another another class class that that will will represent represent aa mix mix loan. loan. ItIt is is aa loan loan where where in in the the first first periods periods I will will write write another another class class that that will will represent represent aa mix mix loan. loan. It It is is aa loan loan where where in in the the first first periods periods there there isis no no repayment, repayment, and and where where you you must must pay pay interest interest only. only. After After the the periods periods without without there there is is no no repayment, repayment, and and where where you you must must pay pay interest interest only. only. After After the the periods periods without without repayment repayment the the loan loan isis an an annuity, annuity, but but with with aa fewer fewer periods. periods. The The class class may, may, for for example example be be repayment repayment the the loan loan is is an an annuity, annuity, but but with with aa fewer fewer periods. periods. The The class class may, may, for for example example be be written written as as follows: follows: written written as as follows: follows: package loanprogram; package package loanprogram; loanprogram;

107 107 107 107

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance InherItanCe

public class MixLoan extends Loan { private int free; private Loan loan; public MixLoan(double principal, double interestRate, int periods, int free) { super(principal, interestRate, periods); this.free = free; loan = new Annuity(principal, interestRate, periods – free); } public int getFree() { return free; } public double payment(int n) { return n <= free ? principal * interestRate : loan.payment(n – free); }

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge

108 108

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Inheritance InherItanCe InherItanCe InherItanCe

public double interest(int n) public double public double interest(int interest(int n) n) { { { return n <= free ? principal * interestRate : loan.interest(n – free); return n <= free ? principal * interestRate : loan.interest(n – free); } return n <= free ? principal * interestRate : loan.interest(n – free); } } public double repayment(int n) public double public double repayment(int repayment(int n) n) { { { return n <= free ? 0 : loan.repayment(n – free); return n <= free ? 0 : loan.repayment(n – free); } return n <= free ? 0 : loan.repayment(n – free); } } public double outstanding(int public double public double outstanding(int outstanding(int { { { return n <= free ? principal return n <= free ? principal } return n <= free ? principal } }} } }

n) n) n) : loan.outstanding(n – free); : : loan.outstanding(n loan.outstanding(n – – free); free);

You should note that a derived class can add new variables (in this case two) and new Youshould should note that derived class can add new variables (in this case two) and new You You shouldnote notethat thataaaderived derivedclass classcan canadd addnew newvariables variables(in (inthis thiscase casetwo) two)and andnew new methods (here the method getFree() that returns the number of periods without repayment). methods (here the method getFree() that returns the number periods without repayment). methods methods(here (herethe themethod methodgetFree() getFree()that thatreturns returnsthe thenumber numberofof ofperiods periodswithout withoutrepayment). repayment). The implementation of the four abstract methods are simple and are not further explained. The implementation of the four abstract methods are simple and are not further explained. The implementation of the four abstract methods are simple and are not further The implementation of the four abstract methods are simple and are not furtherexplained. explained. You can test the class in main(): You can test the class in main(): You Youcan cantest testthe theclass classininmain(): main(): public static void main(String[] args) public static public static void void main(String[] main(String[] args) args) { { { new Amortization(new MixLoan(10000, 0.015, 10, 3)).print(); new Amortization(new MixLoan(10000, 0.015, 10, 3)).print(); } new Amortization(new MixLoan(10000, 0.015, 10, 3)).print(); } }

As another example of aaa loan, loan, one one can can consider consider aaa serial serial loan loan that that isis a loan where the As As another example loan where the As another another example example ofof of a loan, loan, one one can can consider consider a serial serial loan loan that that is is aaa loan loan where where the the repayment is the same for every time. This means that payment is greatest at the beginning repayment is the same for every time. This means that payment is greatest at the beginning repayment is the same for every time. This means that payment is greatest at the beginning repayment is the same for every time. This means that payment is greatest at the beginning and decreases through the loan period. Just asan anAnnuity Annuitythe theproject projecthas hasaaaclass classSerial Serialthat that and and decreases through the loan period. Just anddecreases decreasesthrough throughthe theloan loanperiod. period.Just Justasas as an an Annuity Annuity the the project project has has a class class Serial Serial that that is a derived class that inherits Loan and thus a concrete class. I will not show the code here. isis derived class that inherits Loan and thus concrete class. will not show the code here. isaaaderived derivedclass classthat thatinherits inheritsLoan Loanand andthus thusaaaconcrete concreteclass. class.I IIwill willnot notshow showthe thecode codehere. here. The abstractclass classLoan Loancan canbe bedefined definedby byan aninterface: interface: The abstract The The abstract abstract class class Loan Loan can can be be defined defined by by an an interface: interface: package loanprogram; package package loanprogram; loanprogram; public interface ILoan public interface public interface ILoan ILoan { { { public double getPrincipal(); public double getPrincipal(); public public double double getPrincipal(); getInterestRate(); public double getInterestRate(); public getInterestRate(); public double int getPeriods(); public int getPeriods(); public getPeriods(); public int double repayment(int n); public double repayment(int n); public double n); public double repayment(int interest(int n); public double interest(int n); public n); public double double interest(int payment(int n); public double payment(int n); public double payment(int n); public double outstanding(int n); public double outstanding(int n); } public double outstanding(int n); } }

109 109 109 109

JAVA JAVA3: 3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Inheritance InherItanCe

An An interface interface consists consists only only in in principle principle of of abstract abstract methods, methods, but but itit isis not not necessary necessary to to write write the the word word abstract, abstract, but but itit isis allowed. allowed. The The word word abstract abstract isis default. default. The The class class Loan Loan must must then then implement implement the the interface interface ILoan. ILoan. This This means means that that you you can can delete delete the the four four abstract abstract methods, methods, since since they they are are defined defined in in the the interface, interface, but but the the class class must must still still be be abstract abstract because because itit does does not not implement implement all all of of the the interface interface methods: methods: package loanprogram; public abstract class Loan implements ILoan { protected double principal; // the amount borrowed inc. costs protected double interestRate; // interest rate as a number between 0 and 1 protected int periods; // the number of periods public Loan(double principal, double interestRate, int periods) { this.principal = principal; this.interestRate = interestRate; this.periods = periods; } public double getPrincipal() { return principal; } public double getInterestRate() { return interestRate; }

}

public int getPeriods() { return periods; }

thenpossible possible(and (andyou youshould shoulddo dothat) that)to tochange changethe theclass classAmortization, Amortization,where wherethe thetype type ItItisisthen of the the variable variable loan loan isis changed changed to to ILoan, ILoan, and and the the same same for for the the parameter parameter in in the the constructor. constructor. of

110 110

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance

EXERCISE 7 In problem 1 in the book Java 2 you have written a loan calculation program that calculates the payment of an annuity and shows an amortization table. In this exercise you must create an expansion of this program so that it also can perform loan calculations for a mix loan and a serial loan. Start by creating a copy of the project LoanCalculator from Java 2 and open the copy in NetBeans. Copy the types ------

ILoan Loan Annuity MixLaan Serial

111

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance

from the above project. Next, edit the user interface as shown below. There is added a combo box to select the type of the loan and a combo box for selecting the number of free years. If it not is a mix loan, the value of the last combo box just should be ignored. Finally, the texts of the two final fields are changed such they now respectively shows the first payment and the overall payment for the first year (the payment is not longer necessarily constant). You must then modify the model (quite a bit) so that it uses the loan types from LoanProgram and you must also modify the controller a bit.

PROBLEM 2 The concept of a number sequence is known from mathematics and is a sekvense of numbers. One example is the sequence of even numbers: 0, 2, 4, 6, 8, 10, … where you constantly determines the next number by adding 2. In the same way you can consider the sequence of powers of 2 and the factorials which are 1, 2, 4, 8, 16, 32, 64, 128, … 1, 1, 2, 6, 24, 120, 720, 5040, …

112

1, 2, 4, 8, 16, 32, 64, 128, ... JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance

1, 1, 2, 6, 24, 120, 720, 5040, ...

AtAt the powersofof2 you 2 you always gostep oneforward step forward by multiplying bythe2,factorials while atyou thego the powers always go one by multiplying by 2, while at a step forward byamultiplying by by the multiplying next positive by integer. Morepositive precisely, a number sequence is a factorials you go step forward the next integer. More precisely, sequence of numbers a number sequence is a sequence of numbers 𝑎𝑎0 , 𝑎𝑎1 , 𝑎𝑎2 , . . . , 𝑎𝑎𝑛𝑛 , . ..

where there forfor any integeris isattached attached a (usually) real number. Taking as anynon non negative negative integer a (usually) real number. Taking as example wherewhere therethere for any non negative integer is attached a (usually) real number. Taking as example the the example the consisting sequence consisting ofof the powers 2, writes you sometimes write 76ofwrites sequence the powers 2,sometimes you sometimes sequence consisting of theof powers of 2, you where there for any non negative integer is attached a (usually) real number. Taking as example the 𝑛𝑛 } sequence consisting of the powers of 2, you sometimes writes {2𝑛𝑛 }{2 Insequence this sequence example = 1024..{2𝑛𝑛 } In this this sequence asasexample isis=𝑎𝑎10 In as example is 𝑎𝑎10 1024.

Insequence this problem, you should write some classes that represent represent sequences, but whose InIn asyou example is write 𝑎𝑎10write = 1024. Inthis this problem, youshould should some classes sequences, butonly onlysequences sequences this problem, some classes thatthat represent sequences, but only sequences whose values are integers. values are integers. whose values are integers. In this problem, you should write some classes that represent sequences, but only sequences whose Some sequences - fatorial like fatorial - is growing rapidly, and must sequences implemented in Java, values are integers. Some sequences - like - is –growing very very rapidly, and must sequences implemented in Java, is is Somelimited sequences – like fatorial is growing very rapidly, and must sequences implemented in how big integers yourepresent. can represent. you here sequences integer limited in how big integers you can SinceSince you here only only worksworks with with sequences with with integer in Java, is limited in how big integers you can represent. Since you here only works with values, the issize limited the type you again the factorial Some sequences - limited likeis fatorial -byis growing andconsider must implemented in Java, is values, the size by the type long.long. Ifvery youIfrapidly, again consider thesequences factorial sequences with integer values, the size is limited by the type you again limited in how big integers you can represent. Since you here only workslong. withIfsequences withconsider integer the factorial 20! 2432902008176640000 values, the size is limited by the type If=you again consider the factorial 20!long. = 2432902008176640000

it islargest the largest fatorial that can be represented a long. however, a solution the form 20!be =represented 2432902008176640000 and itand is the fatorial that can by a by long. Java,Java, however, has ahas solution in theinform a class BigInteger, a software implementation an integer. In principle, the class of a of class BigInteger, whichwhich is a is software implementation of anofinteger. In principle, the class arbitrary large integers, itrepresented costs on form very and thethe largest fatorial that can represented by obviously a long. Java, however, has acalculations solution the represents arbitrary large integers, but itbut costs obviously something since calculations oninavery largelarge andit represents itis is largest fatorial thatbe can be by a something long. Java,since however, has solution numbers becomes slow. Nevertheless, theimplementation class is worth knowing, soexample. this example. of class BigInteger, which is a software ofimplementation an integer. In principle, the class numbers becomes Nevertheless, the class isisworth knowing, so this in athe form of slow. a class BigInteger, which a software of an integer. In represents arbitrary large integers, but it costs obviously something since calculations on very large principle, the class represents arbitrary large integers, but it costs obviously something since In following the following you can think of a sequence, a sequence ofexample. numbers number numbers becomes slow. Nevertheless, class is worth knowing, so In the you can think of athe sequence, as a as sequence ofthis numbers wherewhere each each number is is calculations on very large numbers becomes slow. Nevertheless, the class is worth knowing, identified an index, but only one of these numbers are visible the sequence's current identified by anbyindex, but only one of these numbers are visible and isand theissequence's current value.value. so this example. I have illustrated theof sequence consisting powers of 2, and there it isnumber the number 256 InBelow theBelow following you canthe think a sequence, as a of sequence numbers each number is with I have illustrated sequence consisting of powers of 2,of and there it where is the 256 with the index isbut visible: identified by an8,index, only one of these numbers are visible and is the sequence's current value. the index 8, that isthat visible: In theI following you can think of consisting a sequence, a sequence of there numbers where each256 number Below have illustrated the sequence of as powers of 2, and it is the number with the index 8, thatby is visible: is identified an index, but only one of these numbers are visible and is the sequence’s

current value. Below I have illustrated the sequence consisting of powers of 2, and there it is the number 256 with the index 8, that is visible: Create a project Sequences. the following interface, the comments explains Create a project calledcalled Sequences. Add Add the following interface, wherewhere the comments explains what what the the methods should methods should do: do: Create a project called Sequences. Add the following interface, where the comments explains what the package sequences; package sequences; methods should do: import java.math.*; import java.math.*; package sequences; /** /** import* java.math.*; Defines a number sequence integer numbers where the first index is 0. * Defines a number sequence withwith integer numbers where the first index is 0. */ */ /** public interface ISequence public interface ISequence * Defines a number sequence with integer numbers where the first index is 0. { { */ /** /** public interface ISequence * @return of sequence the sequence 113 * @return NameName of the { */ */

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance InherItanCe

Create a project called Sequences. Add the following interface, where the comments explains what the methods should do: package sequences; import java.math.*; /** * Defines a number sequence with integer numbers where the first index is 0. */ public interface ISequence { /** * @return Name of the sequence */ public String getName(); /** * @return The current index */ public int getIndex();

114

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance InherItanCe

/** * @return The current value */ public BigInteger getValue(); /** * Returns the number in the sequence having the index n. At the same time, * this number is the actual value. * @param n The index the sequence must be set to * @return Sequence's value for the index n * @throws Exception If the index is less than 0 */ public BigInteger getValue(int n) throws Exception; /** * Steps the sequens one step forward */ public void next(); /** * Step the sequence one step back * @throws Exception If the index is 0 */ public void prev() throws Exception; /** * Sets the sequence of the first value that is greater than or equal to number. * This value is then the sequence's current value. * @param number The number the sequence to be set by */ public void next(BigInteger number);

}

/** * Sets the sequence of the first value that is less than or equal to number. * This value is then the sequence's current value. * @param number The number the sequence to be set by * @throws Exception If it not is possible to set the sequence at the value */ public void prev(BigInteger number) throws Exception;

You must observe the import of the package java.math. It’s the package containing the class You must observe the import of the package java.math. It’s the package containing the class BigInteger. BigInteger.

115 115

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Inheritance InherItanCe

A sequence is characterized by eight methods, and some of these methods does not depend on a specific sequence. You should then write an abstract class Sequence, which implements everything that is common to all sequences. This class will then be a common base class for specific sequences. As a next step you must implement the sequence consisting of the powers of 2. The class is a concrete sequence and should be implemented as a class that inherits Sequence. Once you have written the class, you should write the following test program (in the main class): public class Sequences { public static void main(String[] args) { print(new Power2(), 50); }

}

private static void print(ISequence s, int n) { try { for (int i = 0; i <= n; ++i, s.next()) System.out.println(s); while (s.getIndex() > 0) { s.prev(); System.out.println(s); } } catch (Exception ex) { System.out.println(ex.getMessage()); } }

Next, Next, write write aa class class that that implements implementsthe thefatorial, fatorial,and andaatest testclass classin inthe thesame sameway wayasasshown shownabove. above.

116 116

}

System.out.println(ex.getMessage());

} } JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance

Next, write a class that implements the fatorial, and a test class in the same way as shown above.

Then, implements and test further three sequences:

Then, implements and test further three sequences:

1. Power, where the1.constructor hasthea constructor parameter, is a BigInteger. If this parameter Power, where hasthat a parameter, that is a BigInteger. If this parameter is called t 2 3 4 5 is called t, the sequence represents the numbers: the sequence represents the numbers: 1, 𝑡𝑡, 𝑡𝑡 , 𝑡𝑡 , 𝑡𝑡 , 𝑡𝑡 , . .. 2. Fibonacci, that represents the fibonacci 0, 8, 1, 1, 2, 21, 3, 5,34, 8, 13, 21,… 34, 55, ... 2. Fibonacci, that represents the fibonacci numbers: 0, 1, numbers: 1, 2, 3, 5, 13, 55, 3. Prime, represents the prime2,numbers: 2, 3,11, 5, 7,13, 11, 13, 19, 23, 23, 29, 31, 37, .... 3. Prime, that represents thethatprime numbers: 3, 5, 7, 17,17,19, 29, 31, 37, ….

With regard to the last sequence you should examine the documentation for the class BigInteger as i actually has a function that with reasonable probability can test whether an integer is a prime.

With regard to the last sequence you should examine the documentation for the class After have implemented these three sequences and tested work properly, change the BigInteger as it actually hasyou a function that with reasonable probability can that test they whether an integer is a prime. class Power2 such it inherits the class Power. After you have implemented these three sequences and tested that they work properly, 4.1 More about inheritance change the class Power2 such it inherits the class Power.

Above I have dealt with the most important concerning inheritance, but there are some details back The kind of inheritance, as discussed above, is called for linear inheritance, which means that a clas can only inherit one class - a class can have only one base class. On the other hand, a class can have al the derived classes, as may be needed, and you can inherit in all the levels as you wish. Inheritance leads to a hierarchy of classes. As an example the classes concerning loans has the following hierarchy:

79

Challenge the way we run

EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…

READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM

1349906_A6_4+0.indd 1

22-08-2014 12:56:57

117

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Inheritance

4.1 MORE ABOUT INHERITANCE Above I have dealt with the most important concerning inheritance, but there are some details back. The kind of inheritance, as discussed above, is called for linear inheritance, which means that a class can only inherit one class – a class can have only one base class. On the other hand, a class can have all the derived classes, as may be needed, and you can inherit in all the levels as you wish. Inheritance leads to a hierarchy of classes. As an example the classes concerning loans has the following hierarchy:

ILoan is an interface, but it is included in the type hierarchy in the same manner as classes. As another example, consider class hierarchy from problem 2:

If a class can inherit several classes, wee talk about multiple inheritance, but Java supports only linear inheritance. Java does indirectly support multiple inheritance when a class can implement all the interfaces that are needed. It is not inheritance, but it means that at design time where you decide which classes a program must consist of, can work with multiple inheritance. You can design classes that implements multiple interfaces.

118

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

5 5 5 5

the Class objeCt The the class Class Object objeCt the the Class Class objeCt objeCt

THE CLASS CLASS OBJECT OBJECT THE THE CLASS OBJECT

Java has a class called Object, and all classes inherits directly or indirectly this class. If, as Java Java has has aa class class called called Object, Object, and and all all classes classes inherits inherits directly directly or or indirectly indirectly this this class. class. If, If, as as Java has called all an looking at Object, the classand Loan Javaexample has aa class class called Object, and all classes classes inherits inherits directly directly or or indirectly indirectly this this class. class. If, If, as as an an example example looking looking at at the the class class Loan Loan an example example looking looking at at the the class class Loan Loan an public public public public

abstract abstract abstract abstract

class class class class

Loan Loan Loan Loan

implements implements implements implements

ILoan ILoan ILoan ILoan

the class automatically inherits the class Object. It means that you could have written the the class class automatically automatically inherits inherits the the class class Object. Object. It It means means that that you you could could have have written written the the class class automatically automatically inherits inherits the the class class Object. Object. It It means means that that you you could could have have written written public abstract class Loan extends Object implements ILoan public abstract class Loan Object implements public Loan extends extends implements ILoan ILoan extends Object Object implements public abstract abstract class class Loan ILoan

and indeed it is allowed to write – but unnecessary. This means several things, including as and and indeed indeed itit isis allowed allowed to to write write –– but but unnecessary. unnecessary. This This means means several several things, things, including including as as and is to unnecessary. This means including as perhaps the it important that – classes in Java are a largethings, hierarchy with the and indeed indeed itmost is allowed allowed to write write –allbut but unnecessary. Thislinked meansinseveral several things, including as perhaps perhaps the the most most important important that that all all classes classes in in Java Java are are linked linked in in a a large large hierarchy hierarchy with with the the perhaps the most important that all classes in Java are linked in a large hierarchy with the class Object the important root. All classes without is an Object inherits the properties perhaps the as most that all classesexception in Java are linked in and a large hierarchy with the class class Object Object as as the the root. root. All All classes classes without without exception exception is is an an Object Object and and inherits inherits the the properties properties class Object ashas. the root. root. All All classes classes without without exception exception is is an an Object Object and and inherits inherits the the properties properties as anObject Objectas class the as as an an Object Object has. has. as an Object has. The class Object defines a few basic methods that all has a trivial implementation, and it is The The class class Object Object defines defines aa few few basic basic methods methods that that all all has has aaa trivial trivial implementation, implementation, and and itit isis The defines basic methods that all and it then up toObject the individual classes to override that implementation, they get a reasonable The class class Object defines aa few few basic methods the thatmethods all has has asotrivial trivial implementation, and use. it is is then then up up to to the the individual individual classes classes to to override override the the methods methods so so that that they they get get a a reasonable reasonable use. use. then up upI to to the individual individual classes toimportant override the the methodsand so Ithat that they get reasonable use. Below briefly mention the mostto methods, willthey use get the aaclasses from use. the then the classes override methods so reasonable Below Below I I briefly briefly mention mention the the most most important important methods, methods, and and I I will will use use the the classes classes from from the the Below briefly most and will project The classthe Subject defined inmethods, the following Below IIStudents. briefly mention mention the most isimportant important methods, and II way will use use the the classes classes from from the the project project Students. Students. The The class class Subject Subject isis defined defined in in the the following following way way project Students. The class Subject is defined in the following way project Students. The class Subject is defined in the following way public public public public

class class class class

Subject Subject Subject Subject

implements implements implements implements

ISubject ISubject ISubject ISubject

, , , ,

IPoint IPoint IPoint IPoint

where its methods are defined in two interfaces. The class also has a toString() method where where its its methods methods are are defined defined in in two two interfaces. interfaces. The The class class also also has has aaa toString() toString() method method where where its its methods methods are are defined defined in in two two interfaces. interfaces. The The class class also also has has a toString() toString() method method public String public String public { public String String { { return navn; { navn; return } return return navn; navn; } } }

toString() toString() toString() toString()

which returns returns the the subject’s subject’s name name as as aa String. String. If If you you now now remove remove this this method method (comment (comment itit which which returns the subject’s name as aa String. If you now remove this method (comment it which returns the subject’s name as String. If you now remove this method out) and perform the following method: which returns the the subject’s namemethod: as a String. If you now remove this method (comment (comment it it out) and perform following out) and perform the following method: out) and perform the following method: out) and perform the following method: private static void test01() private static void test01() private { private static static void void test01() test01() { { try { try try { try { { ISubject subject = Factory.createSubject("MAT7", { ISubject subject = Factory.createSubject("MAT7", ISubject System.out.println(subject); ISubject subject subject = = Factory.createSubject("MAT7", Factory.createSubject("MAT7", System.out.println(subject); System.out.println(subject); 7"); subject.setName("Matematics System.out.println(subject); subject.setName("Matematics 7"); subject.setName("Matematics System.out.println(subject); subject.setName("Matematics 7"); 7"); System.out.println(subject); } System.out.println(subject); System.out.println(subject); } } }

119 119 119 119 119 119

"Matematics"); "Matematics"); "Matematics"); "Matematics");

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

The class Object the Class objeCt

catch (Exception ex) { System.out.println(ex.getMessage()); }

you you get get the the result: result: students.Subtect@6d06d69c students.Subject@6d06d69c

This e-book is made with

SETASIGN

SetaPDF

PDF components for PHP developers

www.setasign.com 120 120

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

The class Object the the Class Class objeCt objeCt the Class objeCt

subject is ananobject, and when System.out.println() prints an object, it isisthe result ofofthe subject subject is is an object, object, and and when when System.out.println() System.out.println() prints prints an an object, object, it it is the the result result of the the subject is an object, and when System.out.println() prints an object, it is the result of the object’s toString() method that is printed. If now the object’s class does not have a atoString() object’s toString() method that is printed. If now the object’s class does not have toString() object’s toString() method that is printed. If now the object’s class does not have a toString() object’s –toString() method is printed. If now thefrom object’s a toString() method such asasthe class that Subject – ititisistoString() the class base does class not thathave is performed, method method – – such such as the the class class Subject Subject – – it is toString() toString() from from the the base base class class that that is is performed, performed, method – case suchitit asis the class Subject – itclass is toString() from theObject base has classa athat is performed, and in this toString() from the Object. The class default toString() and and in in this this case case it is is toString() toString() from from the the class class Object. Object. The The class class Object Object has has a default default toString() toString() and in this case it is toString() from the class Object. The class Object has a default toString() method that prints the class’s name followed by a number. The number is the reference to method method that that prints prints the the class’s class’s name name followed followed by by aa number. number. The The number number is is the the reference reference to to method that prints the class’s name followed by a number. The number is the reference to the object on the heap specified asasa ahexadecimal number. Of course ititmakes no particular the object on the heap specified hexadecimal number. Of course makes no particular the object on the heap specified as a hexadecimal number. Of course it makes no particular the object the heap specified a hexadecimal number. Of course it makes no precisely particular sense, but ititon means that all objectsas can be printed with System.out.println(), or more sense, sense, but but it means means that that all all objects objects can can be be printed printed with with System.out.println(), System.out.println(), or or more more precisely precisely sense, but itameans that all objects can be printed with or more precisely that one has representation ofofany object asasa atext. ItItisSystem.out.println(), then up totothe programmer of the that one has a representation any object text. is then up the programmer that one has a representation of any object as a text. It is then up to the programmer of of the the that one has a representation of any object as a text. It is then up to the programmer of the object’s class to override the toString() so that it returns a reasonable result. I will immediately object’s object’s class class to to override override the the toString() toString() so so that that it it returns returns aa reasonable reasonable result. result. II will will immediately immediately object’sthe class to override the toString()method so that in it returns a reasonable result. I will immediately remove comments for toString() the class Subject again: remove the comments for toString() method in the class Subject again: remove the comments for toString() method in the class Subject again: remove the comments for toString() method in the class Subject again: Matematics Matematics Matematics Matematics Matematics 7 7 Matematics 7

IfIf you the above method writes the statement Ifyou youinin inthe theabove abovemethod methodwrites writesthe thestatement statement If you in the above method writes the statement String String s s = = "The "The subject: subject: " " + + subject; subject; String s = "The subject: " + subject;

the the result will that the variable has the value theresult resultwill willbebe bethat thatthe thevariable variables sshas hasthe thevalue value the result will be that the variable s has the value Subject: Subject: Matematics Matematics 7 7 Subject: Matematics 7

The reason that the plus operator interpreted string concatenation, and since subject The Thereason reasonisis isthat thatthe theplus plusoperator operatorisis isinterpreted interpretedasas asstring stringconcatenation, concatenation,and andsince sincesubject subject The reason is that the plus operator is interpreted as string concatenation, and since subject is an object, it is the value of this object’s toString(), that is concateneted. Incidentally, the isisananobject, object,ititisisthe thevalue valueofofthis thisobject’s object’stoString(), toString(),that thatisisconcateneted. concateneted.Incidentally, Incidentally,the the is an object, it is the value of this object’s toString(), that is concateneted. Incidentally, the result would the same you wrote: result resultwould wouldbebe bethe thesame sameifif ifyou youwrote: wrote: result would be the same if you wrote: String String s s = = "The "The subject: subject: " " + + subject.toString(); subject.toString(); String s = "The subject: " + subject.toString();

Another method the class Object called getClass(), and returns object the type Anothermethod methodinin inthe theclass classObject Objectisis iscalled calledgetClass(), getClass(),and anditit itreturns returnsanan anobject objectofof ofthe thetype type Another Another method in the class Object is called getClass(), and it returns an object of the type Class which contains information about an object’s class – and there are many. Consider as Class which contains information about an object’s class – and there are many. Consider Class which contains information about ananobject’s class ––and there are many. Consider asas Class which contains information about object’s class and there are many. Consider as an example the following method: an example the following method: ananexample examplethe thefollowing followingmethod: method: private private static static void void test02() test02() private static void test02() { { { try try try { { { ISubject subject = Factory.createSubject("MAT7", "Matematics"); ISubject subject = Factory.createSubject("MAT7", "Matematics"); ISubject subject = Factory.createSubject("MAT7", "Matematics"); print(subject); print(subject); print(subject); } } } catch catch (Exception (Exception ex) ex) catch (Exception ex) { { {

121 121 121 121

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

}

}

The class Object the the Class Class objeCt objeCt

System.out.println(ex.getMessage());

private static void print(Object obj) { System.out.println(obj.getClass().getName()); for (Method m : obj.getClass().getMethods()) System.out.println(m.getName()); }

Note Notethat thatthe themethod methodprint() print()use useaaclass classMethod, Method,that thatisisdefined definedininthe thepackage package java.lang.reflect

The Themethod methodprint() print()has hasaaparameter parameterofofthe thetype typeObject, Object,and andfor forthis thisobject objectititprints printsthe the name nameofofthe theobject’s object’sclass, class,and andthe thenames namesofofthe theobject’s object’smethods. methods.The Themethod methodtest02() test02() creates an object of the type Subject and sends it as a parameter to the print() method. creates an object of the type Subject and sends it as a parameter to the print() method.The The result resultisisthe thefollowing: following: students.Subject getECTS setECTS setName getName toString getId wait wait wait equals hashCode getClass notify notifyAll

You Youshould shouldnote notethe theclass classname, name,and andthe theobject objectisisaaSubject, Subject,although althoughininthe themethod methodtest02() test02() isisknown knownasasan anISubject. ISubject.You Youshould shouldalso alsonote notethat thatthe themetod metodprint() print()prints printsthe thenames namesofof total total14 14methods. methods.It’s It’sall allpublic publicmethods, methods,and andititisisfar farmore morethan thanthe theclass classSubject Subjectdefines, defines, but butthe therest restcomes comesfrom fromthe theclass classObject Object––that thatyou youknow knowisisthe thebase baseclass classfor forSubject. Subject. AAClass Classobject objecthas hasmany manymethods, methods,sosoyou youcan canget getmany manydetails detailsregarding regardingan anobject. object.The The method methodgetClass() getClass()can cannot notbe beoverridden. overridden.

122 122 122

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

The Object the class Class objeCt

The class class Object Object also also has has aa method method called called equals() equals() which which has has aa parameter parameter of of the the type type Object Object The and and is is used used to to test test whether whether two two objects objects are are the the same. same. Consider Consider then then the the following following method: method: private static void test03() { try { ISubject subject1 = Factory.createSubject("MAT7", "Matematics"); ISubject subject2 = Factory.createSubject("MAT7", "Matematics"); System.out.println(subject1.equals(subject2)); } catch (Exception ex) { System.out.println(ex.getMessage()); } }

The The you you

method creates two objects of the type Subject and tests whether they are the same. If method creates two objects of the type Subject and tests whether they are the same. If executes the method, you get the result executes the method, you get the result

false

www.sylvania.com

We do not reinvent the wheel we reinvent light. Fascinating lighting offers an infinite spectrum of possibilities: Innovative technologies and new markets provide both opportunities and challenges. An environment in which your expertise is in high demand. Enjoy the supportive working atmosphere within our global group and benefit from international career paths. Implement sustainable ideas in close cooperation with other specialists and contribute to influencing our future. Come and join us in reinventing light every day.

Light is OSRAM

123 123

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA

the Class objeCt the class Class Object objeCt The

which is not really what one would expect. The method equals() is defined in the class which isis not not really really what what one one would would expect. expect. The The method method equals() equals() isis defined defined in in the the class class which Object, and works by comparing the two objects addresses and thus whether they refer to Object, and and works works by by comparing comparing the the two two objects objects addresses addresses and and thus thus whether whether they they refer refer to to Object, the same object on the heap. In this case refers subject1 and subject2 to different objects, the same same object object on on the the heap. heap. In In this this case case refers refers subject1 subject1 and and subject2 subject2 to to different different objects, objects, the and therefore returns equals() false. Now if you want the comparison instead to be done and therefore therefore returns returns equals() equals() false. false. Now Now ifif you you want want the the comparison comparison instead instead to to be be done done and by from the objects’ values or state, it is up to the programmer to override the method in by from from the the objects’ objects’ values values or or state, state, itit isis up up to to the the programmer programmer to to override override the the method method in in by the concrete class. the concrete concrete class. class. the If you look at the class Subject, I would say that two Subject objects are equal if they have you look look at at the the class class Subject, Subject, II would would say say that that two two Subject Subject objects objects are are equal equal ifif they they have have IfIf you the same id – the value is perceived as a key that can identify a Subject. You can then the same same id id –– the the value value isis perceived perceived as as aa key key that that can can identify identify aa Subject. Subject. You You can can then then the override equals() in the following way: override equals() equals() in in the the following following way: way: override public boolean equals(Object obj) public boolean equals(Object obj) { { if (obj == null) return false; if (obj == null) return false; if (getClass() == obj.getClass()) if (getClass() == obj.getClass()) return id.toUpperCase().equals(((Subject)obj).id.toUpperCase()); return id.toUpperCase().equals(((Subject)obj).id.toUpperCase()); return false; return false; } }

That is, a Subject object is equal to another object, if the other object is not null, and if the That That is, is, aa Subject Subject object object isis equal equal to to another another object, object, ifif the the other other object object isis not not null, null, and and ifif the the other object also is a Subject, and if both of these Subject objects have the same id when other other object object also also isis aa Subject, Subject, and and ifif both both of of these these Subject Subject objects objects have have the the same same id id when when there is no distinction between uppercase and lowercase letters. You should note that the there is no distinction between uppercase and lowercase letters. You should note that there is no distinction between uppercase and lowercase letters. You should note that the the test build on, that the class String overrides equals() such i compare the values af strings. test test build build on, on, that that the the class class String String overrides overrides equals() equals() such such ii compare compare the the values values af af strings. strings. You should also note that there is no distinction on the name or ECTS, and that it is You You should should also also note note that that there there isis no no distinction distinction on on the the name name or or ECTS, ECTS, and and that that itit isis the programmer’s decision how the equals() must be overridden and there could be other the the programmer’s programmer’s decision decision how how the the equals() equals() must must be be overridden overridden and and there there could could be be other other options. If you now executes the method test03() you get result options. If you now executes the method test03() you get result options. If you now executes the method test03() you get result true true

A method, method, which belongs belongs to equals() equals() is hashCode(). The The method returns returns an int, int, and the the AA method, which which belongs to to equals() isis hashCode(). hashCode(). The method method returns an an int, and and the default implementation in in class Object Object returns the the object’s memory memory address. The The method isis default default implementation implementation in class class Object returns returns the object’s object’s memory address. address. The method method is used to to identify identify an an object, object, as as well well as as to to represent represent an an object object as as aa number. number. Later Later II will will show used used to identify an object, as well as to represent an object as a number. Later I will show show applications of of the the method method hashCode(), hashCode(), and and here here II will will also also explaine explaine how how to to overrides overrides this this applications applications of the method hashCode(), and here I will also explaine how to overrides this method, but in in principle you you should always always override hashCode() hashCode() if you overrides overrides equals(). IfIf method, method, but but in principle principle you should should always override override hashCode() ifif you you overrides equals(). equals(). If need be be the the protocol protocol isis that that ifif two two objects objects are are equals, equals, they they must must have have the the same same hash hash code. code. need need be the protocol is that if two objects are equals, they must have the same hash code. Because the class class String overrides overrides hashCode() –– correctly correctly – it can be be overridden in in the class class Because Because the the class String String overrides hashCode() hashCode() – correctly –– itit can can be overridden overridden in the the class Subject as follows: follows: Subject Subject as as follows: public int hashCode() public int hashCode() { { return id.toUpperCase().hashCode(); return id.toUpperCase().hashCode(); } }

124 124 124

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

The class Object the the Class Class objeCt objeCt

The class Object also has a method with the following signature: The The class class Object Object also also has has aa method method with with the the following following signature: signature: protected protected void void finalize() throws Throwable finalize() throws Throwable

Because it isis protected, it can not be called from other classes, but itit can be overridden. Because Because it it is protected, protected, it it can can not not be be called called from from other other classes, classes, but but it can can be be overridden. overridden. The method has not so many uses, and the default implementation performs nothing, but The The method method has has not not so so many many uses, uses, and and the the default default implementation implementation performs performs nothing, nothing, but but the method isis called by the garbage collector when an object isis removed from the heap. the method called by the garbage collector when an object removed from the heap. the method is called by the garbage collector when an object is removed from the heap. You has the possibility, to override the method to add code to be executed when an object You You has has the the possibility, possibility, to to override override the the method method to to add add code code to to be be executed executed when when an an object object isis removed from the heap. removed from the heap. is removed from the heap. The last method in class Object, which I will mention has the following signature: The The last last method method in in class class Object, Object, which which II will will mention mention has has the the following following signature: signature: protected protected Object Object clone() throws CloneNotSupportedException clone() throws CloneNotSupportedException

and again method which you not the immediately can call from another class. The and and isis is again again aaa method method which which you you not not the the immediately immediately can can call call from from another another class. class. The The idea is that the method should create a copy of the current object. A class can override this idea idea isis that that the the method method should should create create aa copy copy of of the the current current object. object. AA class class can can override override this this method implements the interface Cloneable. The default implementation tests whether method method ifif if itit it implements implements the the interface interface Cloneable. Cloneable. The The default default implementation implementation tests tests whether whether the object’s class implements this interface, and if not the method raises an exception. the object’s class implements this interface, and if not the method raises an exception. the object’s class implements this interface, and if not the method raises an exception. extends the definition of the class Subject as follows IfIf If III extends extends the the definition definition of of the the class class Subject Subject as as follows follows public public class class Subject implements ISubject, IPoint, Cloneable Subject implements ISubject, IPoint, Cloneable

the default clone() method will create an object that copy of the current object and the the default default clone() clone() method method will will create create an an object object that that isis is aaa copy copy of of the the current current object object and and hence have variables with the same value as the current object. In many contexts it is hence have variables with the same value as the current object. In many contexts it is ok, hence have variables with the same value as the current object. In many contexts it is ok, ok, but if you want to determine how the copy is created you can be override clone(). If, for but but ifif you you want want to to determine determine how how the the copy copy isis created created you you can can be be override override clone(). clone(). If, If, for for example the object has references to other objects, it may be necessary, and another reason example example the the object object has has references references to to other other objects, objects, itit may may be be necessary, necessary, and and another another reason reason may be that the method in Object protected. In the class Subject you could override the may may be be that that the the method method in in Object Object isis is protected. protected. In In the the class class Subject Subject you you could could override override the the method to something like the following: method to something like the following: method to something like the following: public public Object Object clone() clone() throws throws CloneNotSupportedException CloneNotSupportedException { { Subject Subject subject subject = = null; null; try try { { subject subject = = new new Subject(new Subject(new String(id), String(id), new new String(name), String(name), ects); ects); } } catch catch (Exception (Exception ex) ex) { { } } return return subject; subject; } }

125 125 125 125

Deloitte & Touche LLP and affiliated entities.

JAVA 3: OBJECT-ORIENTED PROGRAMMING

The Class class objeCt Object the

That the creation of a Subject object is wrapped in try/catch it is because I have written the constructor of the class Subject so that it can raise an exception. You should also note that I as actual parameters to the constructor creates copies of the strings. Now it is not really necessary, but is included because it in other contexts, in the case of other class types than String, is often necessary. You should also note that the method is public although in Object it is protected. It is actually allowed on that way to strengthen the visibility of a method such that in a derived class is defined with greater visibility than in the base class. One can, in turn, not reduce visibility. Consider the following method: private static void test04() { try { ISubject subject1 = Factory.createSubject("MAT7", "Matematics"); ISubject subject2 = (Subject)((Subject)subject1).clone(); System.out.println(subject1.equals(subject2)); System.out.println(subject1 == subject2); }

360° thinking

.

360° thinking

.

360° thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers 126

Dis

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

} }

The class Object the Class objeCt the Class objeCt

catch catch (Exception (Exception ex) ex) { { System.out.println(ex.getMessage()); System.out.println(ex.getMessage()); } }

IfIf you execute the method, you get the result: Ifyou youexecute executethe themethod, method,you youget getthe theresult: result: true true false false

because the two objects isisindeed a copy ofofeach other and, therefore equals(). The last because because the the two two objects objects is indeed indeed aa copy copy of each each other other and, and, therefore therefore equals(). equals(). The The last last statement prints false and ititshows that subject1 and subject2 are two different objects. You statement prints false and shows that subject1 and subject2 are two different objects. You statement prints false and it shows that subject1 and subject2 are two different objects. You should note the statement should should note note the the statement statement subject2 ISubject ISubject subject2 = = (Subject)((Subject)subject1).clone(); (Subject)((Subject)subject1).clone();

subject1 the code known object the type ISubject, and does not have clone() subject1 subject1isis isinin inthe thecode codeknown knownasas asanan anobject objectofof ofthe thetype typeISubject, ISubject,and anditit itdoes doesnot nothave havea aaclone() clone() method. Therefore, it is necessary with a type of cast of subject1 to a Subject. The method method. method.Therefore, Therefore,ititisisnecessary necessarywith witha atype typeofofcast castofofsubject1 subject1totoa aSubject. Subject.The Themethod method clone() returns an Object, and therefore it is necessary with a typecast of the return value. clone() returns an Object, and therefore it is necessary with a typecast of the return clone() returns an Object, and therefore it is necessary with a typecast of the returnvalue. value. The concept typecast is elaborated in the next chapter. The concept typecast is elaborated in the next chapter. The concept typecast is elaborated in the next chapter.

127 127 127

JAVA JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Typecast typeCast oF objeCts typeCast of oF objects objeCts

6 6 TYPECAST TYPECAST OF OF OBJECTS OBJECTS III have have previously in Java mentioned typecast of simple types. As an example you can not have previously previously in in Java Java 11 1 mentioned mentioned typecast typecast of of simple simple types. types. As As an an example example you you can can not not explicit explicit copy long to an int because an int may not have enough space. may be necessary explicit copy copy aaa long long to to an an int int because because an an int int may may not not have have enough enough space. space. ItIt It may may be be necessary necessary to to write write something something like like the the following following to to tell tell the the compiler compiler that that t t well well should should be be copied copied to to write something like the following to tell the compiler that t well should be copied to to a:a: a: long long t t = = 123; 123; int a; int a; a a = = (int)t; (int)t;

Also objects can be typecasted, but ititisisnecessary that they belong to the same class hierarchy. Also Also objects objects can can be be typecasted, typecasted, but but it is necessary necessary that that they they belong belong to to the the same same class class hierarchy. hierarchy. Otherwise, you get an exception ifif not the compiler before isis giving an error. Consider as Otherwise, you get an exception not the compiler before giving an error. Consider Otherwise, you get an exception if not the compiler before is giving an error. Consider as as an example the following method: an an example example the the following following method: method: private private static static void void test05() test05() { { try try { { Subject Subject subject1 subject1 = = new new Subject("MAT7", Subject("MAT7", "Matematics"); "Matematics"); ISubject subject2 = subject1; ISubject subject2 = subject1; Subject Subject subject3 subject3 = = (Subject)subject2; (Subject)subject2; System.out.println(subject1.equals(subject2)); System.out.println(subject1.equals(subject2)); System.out.println(subject1.equals(subject3)); System.out.println(subject1.equals(subject3)); System.out.println(subject3.equals(subject2)); System.out.println(subject3.equals(subject2)); // // Course Course course course = = (Course)subject1; (Course)subject1; } } catch catch (Exception (Exception ex) ex) { { System.out.println(ex.getMessage()); System.out.println(ex.getMessage()); } } } }

Here refers subject1, subject2 and subject3 all to the same object. Note that you can write Here Here refers refers subject1, subject1, subject2 subject2 and and subject3 subject3 all all to to the the same same object. object. Note Note that that you you can can write write subjet2 subjet2 = = subjet1 subjet1

for subject1 Subject object and thus specifically an ISubject object. In contrast, the statment for forsubject1 subject1isis isaaaSubject Subjectobject objectand andthus thusspecifically specificallyan anISubject ISubjectobject. object.In Incontrast, contrast,the thestatment statment subjet3 subjet3 = = (Subjet)subjet2 (Subjet)subjet2

128 128 128

JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA

Typecast of typeCast oF objects objeCts

requires aa typecast, typecast, as as subject2 subject2 is is an an ISubject ISubject object, object, which which is is not not necessarily necessarily aa Subject Subject object. object. requires Note the the syntax syntax of of aa typecast, typecast, where where in in front front of of aa variable variable you you write write the the type type to to cast cast to, to, Note in parentheses. parentheses. in By contrast, contrast, the the following following statement statement By Course course = (Course)subject1;

results in a compiler error because Course and Subject not are types from the same class results in a compiler error because Course and Subject not are types from the same class hierarchy. hierarchy.

We will turn your CV into an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? We will appreciate and reward both your enthusiasm and talent. Send us your CV. You will be surprised where it can take you.

129 129

Send us your CV on www.employerforlife.com

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Aalast lastnote noteabout aboutclasses Classes

7 7 A A LAST LAST NOTE NOTE ABOUT ABOUT CLASSES CLASSES As As aa final final note note regarding regarding classes classes II mention mention the the word word final. final. IfIf one one defines defines aa variable variable final final like likeNAME NAMEininthe theclass classInstitution Institution public final static String NAME = "The Linux University";

thismeans meansthat thatthe thevariable variableisisaaconstant, constant,and andits itsvalue valuecan cannot notbe bechanged. changed.Also Alsomethods methods this can be be defined defined final, final, and and aa final final method method can can not not be be overridden overridden inin aa derived derived class. class. IfIf aa can methodisisoverridden overriddenininaaderived derivedclass, class,you youhas hasthe thepossibility possibilitytotowrite writethe themethod methodtotohave have method whole different different meaning, meaning, and and ifif you you do do not not want want itit toto be be possible, possible, you you can can define define the the aa whole methodfinal. final.Also Alsofinal finalclasses classescan canbe bedefined, defined,and andaafinal finalclass classisisaaclass classwhich whichcan cannot notbe be method inherited.As Asan anexample exampleisisthe theString Stringclass classfinal. final. inherited.

7.1 CONSIDERATIONS CONSIDERATIONSABOUT ABOUTINHERITANCE INHERITANCE 7.1 will conclude conclude all all what what isis said said about about interfaces interfaces and and inheritance inheritance with with aa few few remarks. remarks. Seen Seen II will from the the programmer programmer consists consists aa program program ofof classes classes that that defines defines the the objects objects used used by by the the from application toto perform perform its its work. work. For For the the sake sake ofof maintenance maintenance ofof the the program program you you are are application interested that that these these classes classes isis asas loosely loosely coupled coupled asas possible, possible, and and that that is, is, that that the the classes classes interested shouldknow knowso solittle littleabout abouteach eachothers othersasaspossible. possible.In Inthat thatway wayyou youcan canchange changethe theclasses classes should without itit affects affects the the rest rest ofof the the program. program.You You should should therefore therefore strive strive toto write write the the classes, classes, without soaachange changeonly onlyaffects affectsthe theclass classitself itselfand andthus thusonly onlyhas haslocal localsignificance. significance. so Now you you can can not not write write programs programs without without there there are are couplings couplings between between the the classes, classes, the the Now meaning ofof aa class class isis precisely precisely that that itit must must make make services services available available for for others others toto use, use, but but meaning you can can ensure ensure that that the the coupling coupling only only takes takes place place through through public public methods. methods. That’s That’s why why II you sometimes have have talked talked about about data data encapsulation encapsulation where where instance instance variables variables are are kept kept private, private, sometimes andthus thusititbecomes becomesthe theprogrammer programmerwho whothrough throughthe theclass’s class’spublic publicmethods methodsdecides decideswhich which and couplings toto be be possible. possible. This This principle principle can can be be further further supported supported through through an an interface interface ifif couplings all the the classes classes are are defined defined by by an an interface. interface. An An interface interface defines defines through through abstract abstract methods methods all (methodsininan aninterface interfaceare areby bydefault defaultpublic publicabstract), abstract),which whichcouplings couplingsshould shouldbe bepossible, possible, (methods andadhere adheretotoititand andalways alwaysdefine definereferences referencestotoobjects objectsusing usingaadefining defininginterface, interface,you youget get and loosercoupling couplingofofthe theprogram’s program’scomponents componentsasasan anobject objectalone aloneisisknown knownasasan aninterface interface aalooser and the the class class that that implements implements the the interface interface isis not not known known and and may may be be changed changed without without and affects the the rest rest ofof the the program. program. Therefore, Therefore, itit isis aa design design principle principle that that that that you you should should itit affects programtotoan aninterface. interface. program

130 130

JAVA 3: OBJECT-ORIENTED PROGRAMMING

A last note about classes

To program to an interface is a good design principle, but everything can be overstated. A program can easily consist of several hundred classes, and if each (or most) of these classes defines an interface, the number of types will be huge and may lead to code that is difficult to grasp. One should therefore consider, when a class must define an interface and concerning primary classes, which represent key concepts in which there is a chance that there will be changes. A program will always consist of many classes that are using other classes that are local in nature, and these classes should not be defined with an interface. The upshot is that programming to an interface is an important principle and one of the best ways to secure loose couplings between parts of the program, but also that, while developing consider whether an interface makes sense. Another use of interfaces is that using interfaces at design time you can define different contracts that the program’s objects must comply. As a class can implement multiple interfaces (all of them you need), you can create objects that meet multiple contracts, and as some of the most important thing you can test whether an object meets one or the other contract. With reference to the previous chapters, an object defined Cloneable abide by the contract, that it can create a copy of itself. Another interface is called Comparable, and classes that implements this interface, instantiates objects that can be arranged in order and hence, for example be sorted. Java defines a number of such interfaces, which defines one or another property that an object may have. You will later in the book Java 4 about collection classes face classes that implements many interfaces. An interface is a concept that defines contracts which objects must comply. If you look at the interfaces defined in this book, they reflect very closely the classes that implements these interfaces. It does absolutely not necessarily be the case, and many interfaces define a contract in form of a few and perhaps only a single method.

131

JAVA 3: OBJECT-ORIENTED PROGRAMMING

A last note about classes

With regard of inheritance one can say that there are two uses. In one situation you have some classes which are similar, such that they somewhat are comprised of the same variables and methods. In such a situation you can take what the classes have in common, and move it into a common base class, that the others inherits. That way, you avoid the same code can be found in several places and thus have a program that takes up less space, but the important thing is that if you have to change the code, you should only change it at one place, and you are sure that you do not forget to change somewhere. The second situation is that you have defined a concept in the form of a class, and then you need a different concept, similar to the first but might need an extra variable or method, or there may be a method that should work on another way. In this case, the new concept can be defined as a class that inherits the first class. The two situations are really two sides of the same coin, but in the first case we speak of generalization, while in the second case, wee talk about specialization. Whatever’s inheritance reflects the fact that a program consists of classes that have something in common and to model concepts of the same kind, and may be useful to define a hierarchy of classes that inherit each other. At the design level the implementation of an interface also is a form of inheritance as an interface says that an object satisfies a particular contract. Because Java only supports linear inheritance, interfaces help during the design to work with multiple inheritance.

AXA Global Graduate Program Find out more and apply

132

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

A a last last note note about about classes Classes

The The most most important important of of inheritance inheritance isis not not so so much much the the expansion expansion of of existing existing code code (although (although itit isis of of course course also also important), important), but but itit isis the the relationship relationship between between super super class class and and subclass. subclass. If If you you have have aa specialization specialization

(and (and here here itit isis not not so so important, important, ifif A A isis aa class class or or an an interface), interface), itit isis important important that that aa BB isis also also an an AA and and aa BB anywhere anywhere can can be be treated treated in in the the same same way way as as an an A. A. It It means means that that you you can can write write aa method method and and thus thus code code which which treats treats an an AA object: object: type metode(A a) { }

and and the the method method will will work work regardless regardless of of whether whether the the parameter parameter isis an an AA object object or or BB object object or another type that directly or indirectly inherits A. The method does not know or another type that directly or indirectly inherits A. The method does not know the the specific type, and it does not have to do it. It is called polymorphism and is one of the most specific type, and it does not have to do it. It is called polymorphism and is one of the most important important concepts concepts in in object-oriented object-oriented programming programming and and allows allows you you to to write write program program code code that is very flexible and general. that is very flexible and general. Inheritance Inheritance isis one one of of the the basic basic principles principles behind behind object-oriented object-oriented programming programming and and more more than that, for it is a requirement that an object-oriented programming language supports than that, for it is a requirement that an object-oriented programming language supports inheritance. inheritance. However, However, itit isis not not the the solution solution to to everything, everything, and and there there isis also also criticism criticism of of inheritance. Taking the above design where B inherits A, it reflects a strong connection inheritance. Taking the above design where B inherits A, it reflects a strong connection and and itit especially especially ifif AA defines defines protected protected members. members. There There isis aa high high probability probability that that changes changes in in AA will have an impact on derived classes. Moreover, one can mention that the connection will have an impact on derived classes. Moreover, one can mention that the connection between between AA and and BB isis very very static static and and determined determined at at compile-time. compile-time. Sometimes Sometimes one one thinks, thinks, therefore, on a design as therefore, on a design as

wherein wherein an an object object BB knows knows an an AA object object through through aa reference. reference. Here Here reference reference can can be be replaced replaced at runtime, providing the opportunity to the object B that it can refer to another A at runtime, providing the opportunity to the object B that it can refer to another A object, object, and the result is a code that is more flexible. One speaks sometimes that B delegate and the result is a code that is more flexible. One speaks sometimes that B delegate tasks tasks to the A object. The two design principles are not directly each other alternatives, but to the A object. The two design principles are not directly each other alternatives, but in in the last years there has probably been briefed on using delegation in situations where you the last years there has probably been briefed on using delegation in situations where you would would previously previously use use of of inheritance. inheritance.

133 133

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Aalast lastnote noteabout aboutclasses Classes

PROBLEM PROBLEM33 InInthis thistask, task,you youmust mustwrite writesome someclasses classesthat thatare areorganized organizedininaahierarchy. hierarchy.The Theclasses classesare are simple simpleand andrepresent representgeometric geometricobjects, objects,triangles trianglesand andsquares, squares,and andtotothe theextent extentthat thatthere there isisaaneed needfor formathematical mathematicalformulas, formulas,ititisissimple simpleformulas, formulas,which whichare areknown knownfrom fromprimary primary school. school.The Thegoal goalisistotoshow showmany manyofofthe theconcepts conceptsofofclasses classestreated treatedininthis thisbook. book. Start Start by by creating creating aa NetBeans NetBeans project, project, you you can can call call Geometry. Geometry. The The example example treates treates asas mentioned mentionedgeometric geometricshapes, shapes,but butyou youshould shouldonly onlybe beinterested interestedininaashape’s shape’sperimeter perimeterand and area. area.Correspondingly, Correspondingly,aashape shapecan canbe bedefined definedasasfollows: follows: package geometry; /** * Defines a geometrical shape. */ public interface IShape { /** * @return The circumference of the shape */ public double perimeter();

}

/** * @return The area of the shape */ public double area();

andyou youneed needtotoadd addthis thisinterface interfacefor foryour yourproject. project.You Youmust mustthen thenadd addan anauxiliary auxiliaryclass class and thatshould shouldbe becalled calledPoint Pointand andrepresents representsaapoint pointininaaplane planecoordinate coordinatesystem: system: that package geometry; public class Point { public static final double ZERO = 1.0e-20; // represents zero private double x; private double y; public Point(double x, double y) { this.x = x; this.y = y; }

134 134

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

A last note about classes a last note about Classes

public double getX() { return x; } public double getY() { return y; } public double length(Point p) { return Math.sqrt(sqr(x – p.x) + sqr(y – p.y)); } public String toString() { return String.format("(%.4f, %.4f)", x, y); }

I joined MITAS because I wanted real responsibili� I joined MITAS because I wanted real responsibili�

Real work International Internationa al opportunities �ree wo work or placements

135 135

�e Graduate Programme for Engineers and Geoscientists

Maersk.com/Mitas www.discovermitas.com

�e G for Engine

Ma

Month 16 I was a construction Mo supervisor ina const I was the North Sea super advising and the No he helping foremen advis ssolve problems Real work he helping fo International Internationa al opportunities �ree wo work or placements ssolve pr

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

A last note about classes a last note about Classes

public boolean equals(Object obj) { if (obj == null) return false; if (getClass() == obj.getClass()) { Point p = (Point)obj; return Math.abs(x – p.x) <= ZERO && Math.abs(y – p.y) <= ZERO; } return false; } public static double sqr(double x) { {{return x * x; return xx ** x; x; } return

} }}

}}

Regarding the method length(), note that given two points (x , y ) and (x , y ) you determines

2 22 (𝑥𝑥11, 𝑦𝑦𝑦𝑦𝑦𝑦1111) and (𝑥𝑥22, 𝑦𝑦𝑦𝑦𝑦𝑦2222) 2you (𝑥𝑥𝑥𝑥 determines the Regarding the method length(), note that given two points (𝑥𝑥𝑥𝑥 the distance between the points as: distance between the points as:

(𝑦𝑦11 − 𝑦𝑦𝑦𝑦𝑦𝑦22 )22 √(𝑥𝑥11 − 𝑥𝑥𝑥𝑥𝑥𝑥22 )22 + (𝑦𝑦𝑦𝑦 √(𝑥𝑥𝑥𝑥

Also note that the class has a static method sqr() which returns the square of a number. In principle, Also note that the class has a static method sqr() which returns the square of a number. such a method does not have to do with a point and is also just an auxiliary method to implement In principle, such a method does not have to do with a point and is also just an auxiliary length(), but because it may be useful in other contexts, it is defined as a static public method.

method to implement length(), but because it may be useful in other contexts, it is defined as a static publicclass method. Write an abstract Shape that implements the interface in IShape. The class should only overrides

the method equals(), such two shapes are the same, if the objects has the same class, and if the two Write an abstract class Shape and thatarea. implements the interface in IShape. The class should only shapes have the same perimeter

overrides the method equals(), such two shapes are the same, if the objects has the same The class willtwo represent a concrete geometric shape. Theand class should be named Ellipse and must class,next and if the shapes have the same perimeter area.

represents an ellipse, when an ellipse is solely defined by the two radi that are transferred as parameters to the constructor: The next class will represent a concrete geometric shape. The class should be named Ellipse

The next class will represent a concrete geometric shape. The class should be named Ellipse and must represents an ellipse, when an ellipse is solely defined by the two radi that are transferred as parameters to the constructor:

You can calculate the ellipse's perimeter and area on the basis of the following formulas: 𝜋𝜋 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 = 𝑎𝑎𝑎𝑎𝑟𝑟11𝑎𝑎𝑎𝑎𝑟𝑟22𝜋𝜋𝜋𝜋 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎

𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝 2𝜋𝜋√0.5(𝑟𝑟1122 + 𝑎𝑎𝑎𝑎𝑟𝑟2222 ) 𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝 𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 = 2𝜋𝜋𝜋𝜋√0.5(𝑎𝑎𝑎𝑎

With the ellipse in place, you can write a class Circle, representing a circle when a circle is simply an ellipse where the two radi are equal. The class Circle can be written as a class that inherits Ellipse. 136

136Start with a class Polygon, which can represent an As a next step, yot should write classes to triangles.

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Aalast lastnote noteabout aboutclasses Classes

You can calculate the ellipse’s perimeter and area on basis ofofthe following You calculate the ellipse's perimeter and onon the ofofthe following Youcan can calculate the ellipse’s perimeter and area onthe the basis theformulas: followingformulas: formulas: You can calculate the ellipse's perimeter andarea area thebasis basis the following formulas: 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎==𝑟𝑟1𝑎𝑎𝑎𝑎𝑟𝑟12𝑎𝑎𝑎𝑎𝜋𝜋 2 𝜋𝜋𝜋𝜋

2 22 𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝 ) 1 12++𝑟𝑟2𝑎𝑎𝑎𝑎2) 𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎==2𝜋𝜋√0.5(𝑟𝑟 2𝜋𝜋𝜋𝜋√0.5(𝑎𝑎𝑎𝑎

With the ellipse ininplace, you can a class representing aacircle when circle With the ellipse place, you canwrite classCircle, Circle, representing circle when asimply circle With the ellipse ininplace, you awrite representing a acircle a acircle isisasimply anis With the ellipse place, youcan canwrite write aclass classaCircle, Circle, representing circlewhen when circle anis simply an where the two radi are equal. The class can bebeinherits written asasaaclass ellipse where the radi equal. The class Circle can bebewritten as that Ellipse. simply anellipse ellipse where the two radi are equal. The classCircle Circle can written class ellipse where thetwo two radiare are equal. The class Circle can written asa aclass class that inherits Ellipse. that thatinherits inheritsEllipse. Ellipse.

As Asa anext nextstep, step,yot yotshould shouldwrite writeclasses classestototriangles. triangles.Start Startwith witha aclass classPolygon, Polygon,which whichcan canrepresent representanan arbitrary polygon. ItItcan beberepresented by objects are the vertices. The arbitrary polygon. can represented byPoint Point objectsthat that are thepolygon's vertices. Theclass class As step, write to Start with apolygon's which can Asaanext next step,yot yotshould should writeclasses classes totriangles. triangles. Start with aclass classPolygon, Polygon, which can should not validate the corners and test whether they lead to irregular polygons, for example polygons should not validate the corners and test whether they lead to irregular polygons, for example polygons represent representan anarbitrary arbitrarypolygon. polygon.ItItcan canbeberepresented representedby byPoint Pointobjects objectsthat thatare arethe thepolygon’s polygon’s where wheresides sidesintersect. intersect.AApolygon polygoncan canbebewritten writtenasasthe thefollowing followingclass: class:

vertices. vertices.The Theclass classshould shouldnot notvalidate validatethe thecorners cornersand andtest testwhether whetherthey theylead leadtotoirregular irregular polygons, for example polygons where sides intersect. A polygon can be written polygons, for example polygons where sides intersect. A polygon can be written asas the the package geometry; package geometry; following followingclass: class: public publicabstract abstractclass classPolygon Polygonextends extendsFigur Figur {{ package geometry;p; protected // protectedPunkt[] Punkt[] p; //polygonens polygonenshjørner hjørner

public ... p) publicPolygon(Punkt Polygon(Punkt ...Polygon p) public abstract class extends Figur {{ { protected Punkt[] p; // polygonens hjørner

92 92

public Polygon(Punkt … p) { this.p = p; } public double omkreds() { double sum = p[p.length – 1].length(p[0]); for (int i = 1; i < p.length; ++i) sum += p[i – 1].length(p[i]); return sum; }

}

public String toString() { … }

Knowing Knowing the the vertices, vertices, you you can can immediately immediately implements implements the the method method perimeter() perimeter() asas the the circumference can be determined as the sum of the lengths of the edges. However, you can circumference can be determined as the sum of the lengths of the edges. However, you can not notimmediately immediatelyimplement implementthe themethod methodarea(), area(),and andthe theclass classisistherefore thereforedefined definedabstract. abstract.

137 137

}

Knowing the vertices, you can immediately implements the method perimeter() as the circumference can be determined as thePROGRAMMING sum of the lengths of the edges. However, you note can not immediately JAVA 3: OBJECT-ORIENTED A last about classes implement the method area(), and the class is therefore defined abstract.

Next, write a class Triangle, which must be a class that inherits Polygon. The class must have Next, write a class Triangle, which must be a class that inherits Polygon. The class must have a aconstructor constructor that has three points as parameters, and apart from the constructor the class that has three points as parameters, and apart from the constructor the class alone has to alone hasthetotoString() overrideand theimplement toString()the andmethod implement methodthearea(). Regarding the last override area(). the Regarding last you can determine the you can determine the area of a triangle with sides a, b and c as follows: area of a triangle with sides a, b and c as follows:

𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 = ½𝑎𝑎𝑎𝑎√1 − (

2

𝑎𝑎2 + 𝑏𝑏 2 − 𝑐𝑐 2 ) 2𝑎𝑎𝑎𝑎

In the of of other classes the area should be done be by means of using a public static In theinterest interest other classes the calculation area calculation should done by means of using a method that has as parameters has the triangle's vertices. public static method that has as parameters has the triangle’s vertices. The class Triangle represents an arbitrary triangle defined by three points. You can also have more

The class Triangle represents an arbitrary triangle defined by three points. You can also have specialized classes for the triangles, such as Equilateral class representing an equilateral triangle, more triangles, such Triangle. as Equilateral class representing an equilateral which specialized should be aclasses class for thatthe inherits the class The class's constructor must have one triangle, which should be a class that inherits the class Triangle. The class’s constructor parameter that is the side length (note that it is easy to define three points which form the vertices in a must have parameter that is -the (note(0,0)). that For it isperformance easy to define threethepoints triangle withone a certain side length startside withlength the point reasons class should override methodinperimeter(), be implemented effectively you know the which form thethevertices a triangle since with ita can certain side lengthmore – start with theif point (0,0)). side length. Write the class Equilateral. For performance reasons the class should override the method perimeter(), since it can be implemented more effectively if you know the side length. Write the class Equilateral. Write similar to a class RightAngled that represents a right angled triangle.

As the last shapes you should write some classes to squares. Start with a class GeneralSquare, which inherits the class Polygon. The class must have a constructor, which parameters are four Point objects. Furthermore the the class must implements the method area(), which is abstract in the base class. There is no general formula to determine the area of a general square, but you draw a diagonal, that divides the square into two triangles (because I ignore the problem that a square may be concave). You can therefore implement the method area() by determining the area of the two triangles.

93%

OF MIM STUDENTS ARE WORKING IN THEIR SECTOR 3 MONTHS

You must then write a class Rectangle, which inherits the class GeneralSquare when the class's FOLLOWING GRADUATION

93

MASTER IN MANAGEMENT • STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES THAT THE CAPITAL OF SPAIN OFFERS • PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR PROFESSIONAL GOALS • STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS EXPERIENCE

5 Specializations

Personalize your program

www.ie.edu/master-management

#10 WORLDWIDE MASTER IN MANAGEMENT FINANCIAL TIMES

[email protected]

138

Length: 1O MONTHS Av. Experience: 1 YEAR Language: ENGLISH / SPANISH Format: FULL-TIME Intakes: SEPT / FEB

55 Nationalities

in class

Follow us on IE MIM Experience

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING

Aalast lastnote noteabout aboutclasses Classes

Write Writesimilar similartotoa aclass classRightAngled RightAngledthat thatrepresents representsa aright rightangled angledtriangle. triangle. As Asthe thelast lastshapes shapesyou youshould shouldwrite writesome someclasses classestotosquares. squares.Start Startwith witha aclass classGeneralSquare, GeneralSquare, which whichinherits inheritsthe theclass classPolygon. Polygon.The Theclass classmust musthave havea aconstructor, constructor,which whichparameters parametersare are four fourPoint Pointobjects. objects.Furthermore Furthermorethe thethe theclass classmust mustimplements implementsthe themethod methodarea(), area(),which which isisabstract abstractininthe thebase baseclass. class.There Thereisisno nogeneral generalformula formulatotodetermine determinethe thearea areaofofa ageneral general square, square,but butyou youdraw drawa adiagonal, diagonal,that thatdivides dividesthe thesquare squareinto intotwo twotriangles triangles(because (becauseI Iignore ignore the theproblem problemthat thata asquare squaremay maybebeconcave). concave).You Youcan cantherefore thereforeimplement implementthe themethod methodarea() area() by bydetermining determiningthe thearea areaofofthe thetwo twotriangles. triangles. You Youmust mustthen thenwrite writea aclass classRectangle, Rectangle,which whichinherits inheritsthe theclass classGeneralSquare GeneralSquarewhen whenthe theclass’s class’s constructor constructorhas hastwo twoparameters parametersthat thatrespectively respectivelyare arethe thewidth widthand andheight. height.Also, Also,write writea aclass class Square Squarewhen whena asquare squarejust justisisa arectangle rectanglewhere wherethe thesides sidesare areofofequal equallength. length. You’ve You’vewritten writtensome someclasses classesthat thatrepresents representsgeometric geometricobjects, objects,and andyou youmust mustnow nowdefine definea a composite compositeshape, shape,which whichconsists consistsofofother othershapes. shapes.The Thefollowing followinginterface interfaceinherits inheritsIShape IShape and anddefines definesa acomposite compositeshape shapecalled calleda aIDrawing: IDrawing: package geometri; public interface IDrawing extends IShape { public void add(IShape … shape) throws Exception; }

Write Writea aclass classDrawing Drawingthat thatimplements implementsthis thisinterface interfacewhen whenthe thecircumference circumferenceofofa adrawing drawingisis defined definedasasthe thesum sumofofthe theperimeters perimetersofofallallthe thedrawing’s drawing’sshapes shapesand andthe thesame samefor forthe thearea. area. AAdrawing drawingisistherefore thereforeespecially especiallyananIShape, IShape,and andthus thusa adrawing drawingcontains containsother otherdrawings. drawings. Below is a test program that creates a drawing that consists of Below is a test program that creates a drawing that consists of 1. 1.a adrawing drawingthat thatcontains containsa acircle, circle,a aequilateral equilateraland anda arectangle rectangle 2. a right angled triangle 2. a right angled triangle 3. 3.a adrawing drawingthat thatcontains containsa asquare squareand andtwo twocircles circles package geometry; public class Geometry { public static void main(String[] args) {

139 139

JAVA JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Aalast lastnote noteabout aboutclasses Classes a last note about Classes

print(create(create(new Circle(2), new Equilateral(3), new Rectangle(3, 4)), print(create(create(new Circle(2), new Equilateral(3), new Rectangle(3, 4)), new RightAngled(3, 4), create(new Square(5), new Circle(1), new Circle(3)))); new RightAngled(3, 4), create(new Square(5), new Circle(1), new Circle(3)))); }

private static void print(IShape shape) private static void print(IShape shape) { { System.out.println(shape); System.out.println(shape); System.out.println("Perimeter: " + shape.perimeter()); System.out.println("Perimeter: " + shape.perimeter()); System.out.println("Area: " + shape.area()); System.out.println("Area: " + shape.area()); } }

}

private static IShape create(IShape … shapes) private static IShape create(IShape … shapes) { { IDrawing d = new Drawing(); IDrawing d = new Drawing(); try try { { d.add(shapes); d.add(shapes); } } catch (Exception ex) catch (Exception ex) { { System.out.println(ex.getMessage()); System.out.println(ex.getMessage()); } } return d; return d; } } }

Test Testthe theprogram. program.The Theresult resultshould shouldbe besomething somethinglike likethe thefollowing: following: Test the program. The result should be something like the following: Start drawing Start drawing Start drawing Start drawing Circle, r = 2,00000000 Circle, r = 2,00000000 Equilateral: 3 Equilateral: 3 Rectangle: width = 3.0, height = 4.0 Rectangle: width = 3.0, height = 4.0 End drawing End drawing Right angled triangle with kateters: 3.0 and 4.0 Right angled triangle with kateters: 3.0 and 4.0 Start drawing Start drawing Square, side 5.0 Square, side 5.0 Circle, r = 1,00000000 Circle, r = 1,00000000 Circle, r = 3,00000000 Circle, r = 3,00000000 End drawing End drawing End drawing End drawing Perimeter: 92.69911184307752 Perimeter: 92.69911184307752 Area: 90.87941146728707 Area: 90.87941146728707

The Thetypes typesofofthis thistask taskisisorganized organizedininaaclass classhierarchy hierarchyand andcan canbe beillustrated illustratedasasshown shownbelow. below. The types of this task is organized in a class hierarchy and can be illustrated as shown below. It’s It’ssimple simpletotoexpand expandthe theclass classhierarchy hierarchywith withnew newclasses, classes,including includingclasses classesfor fornew newshapes, shapes, It’s simple to expand the class hierarchy with new classes, including classes for new shapes, and as long as these classes complies with the contract IShape, the class Drawing can and as long as these classes complies with the contract IShape, the class Drawing canuse use and as classes long asasthese classesnothing complies withthe theconcrete contractclasses. IShape, the class Drawing can use these it knows about these classes as it knows nothing about the concrete classes. these classes as it knows nothing about the concrete classes.

140 140 140

JAVA 3: OBJECT-ORIENTED PROGRAMMING

A last note about classes

141

JAVA 3: OBJECT-ORIENTED PROGRAMMING

A last note about classes

7.2 THE COMPOSITE PATTERN In fact it is quite often that, in practice, you meat a situation similar to above and think for example on a part list where you have a product that is composed of subcomponents, or think of a menu where a menu consisting of menu items or other menus. Another example is a filesystem consisting of directories and files. Therefore, it is natural to express the situation in a design pattern called a composite pattern. The problem is thus to manipulate a hierarchy of objects, where the bottom of the hierarchy have some concrete objects that we call the leaf objects, and there are some other objects that we call composite objects consisting of leaf objects and other composite objects. Both leaf objects and composite objects have a common base class (and possibly it is an interface or an abstract class), and the idea is that composite objects treat their child objects alike, whether in the case of leaf or composite objects. The solution is illustrated with a figure as shown below and the solution is referred as a composite pattern. In practice, there may be different flavors, and often there may be several kinds of leaf objects that all are part of a hierarchy. This is the case in the above example with geometric shapes. Here, the Component class corresponds to the interface IShape, and the class Leaf corresponding to Shape. In the figure below corresponds the class Composite to IDrawing. In principle, it is a very simple pattern, but in practice there are still some considerations on how to implements the pattern. The goal is as mentioned that the Leaf and the Composite objects must have the same behavior, and therefore the methods addComponent() and removeComponent() is defined in Component. It provides, however, a problem since they do not make sense for Leaf objects. Where necessary, they must in Leaf classes be implemented as methods that do not perform anything and possible raises an exception. If you instead uses a design as shown above, it then is necessary to test whether specific objects are Leaf or Composite objects.

142

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

8 FINAL EXAMPLE 8 Final example As a conclusion of this book, I will write a program that can evaluate matheatical expressions. As a conclusion of this book, I will write a program that can evaluate matheatical expressions. The The user should a mathematical on one or more user should be ablebetoable entertoa enter mathematical expressionexpression that dependthat on depend one or more variables, for variables, example: for example: 2 ∗ sin(𝑥𝑥0) + 𝑠𝑠𝑞𝑞𝑞𝑞𝑞𝑞(5 ∗ 𝑥𝑥1 + 3)

that depends variables. Then the the useruser should enter enter valuesvalues for thefor expression's variables and the that dependsonontwo two variables. Then should the expression’s variables program should then evaluate the expression for these variables. and the program should then evaluate the expression for these variables. If there is an error:

If there is an error: – the user has entered an expression that is not syntactically correct theuser user entered an expression not syntactically correct – --the hashas entered arguments that are notthat legalis compared to the current expression – --anthe error occurs when thearguments expression that is evaluated user has entered are not legal compared to the current expression

-- an error occurs when the expression is evaluated

the program must show an appropriate error message.

the program must show an appropriate error message.

In the example above the expression includes sine and square root. The program should support the most common mathematical functions somewhat similar to what applies for a mathematical calculator, In above the be expression includes sine and root. The program should andthe it is example a desire that it should easy to extend the program withsquare new functions, if the need arises.

support the most common mathematical functions somewhat similar to what applies for aThe mathematical and ituser is ainterface desire where that ityou should be easy to extend program program mustcalculator, have a graphical can enter expressions and the values for the variables. regard toif expressions there are following requirements: with newWith functions, the need arises. An expression is not case sensitive, it should not matter whether write in lowercase or Theprogram must have a graphical userand interface where you can enteryou expressions and values for the uppercase. variables. With regard to expressions there are following requirements: 

   

An expression may contain any number of variables, referred to as x0, x1, x2, ..., that is an x followed by a non-negative integer or number. -- An expression is not case sensitive, and it should not matter whether you write in Numbers is always entered with dot as decimal point. lowercase or uppercase. An expression must support the four common arithmetic operators +, -, * and /. -- An expression may contain any number of variables, referred to as x0, x1, x2, …, It should be allowed to use parentheses in any number of levels. is an x followed non-negative integer or number. Ifthat a mathematical functionby hasa several arguments, they must be separated by comma.

-- Numbers is always entered with dot as decimal point. -- An expression must support the four common arithmetic operators +, -, * and /. It should be allowed to use parentheses in any number of levels. 8.1--Analyse -- If a mathematical function has several arguments, they must be separated by comma. The above can be seen as the requirements for the program. It is always the starting point for a sofware development project, but before you can address the development of the program it is the typical needed to clarify uncertainties or boundaries. This is also true in this case where it is necessary to clarify which functions the program exactly must support and how the user interface should be. A mathematical function is identified by a name and then it can be followed by a parameter list in parentheses. In an expression, it must be possible to use the following functions: 143 97

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

8.1 ANALYSE The above can be seen as the requirements for the program. It is always the starting point for a sofware development project, but before you can address the development of the program it is the typical needed to clarify uncertainties or boundaries. This is also true in this case where it is necessary to clarify which functions the program exactly must support and how the user interface should be. A mathematical function is identified by a name and then it can be followed by a parameter list in parentheses. In an expression, it must be possible to use the following functions: -- constant functions (functions without parentheses) -- pi -- e -- functions in 1 variable -- sin cot sqr -- asin acot sqrt -- cos ln abs -- acos exp frac -- tan log floor -- atan antilog

Excellent Economics and Business programmes at:

“The perfect start of a successful, international career.” CLICK HERE

to discover why both socially and academically the University of Groningen is one of the best places for a student to be

www.rug.nl/feb/education

144

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

-- functions in 2 variables -- pow -- root To define the application user interface I has created a NetBeans project named Calc. The project creates a prototype, which is a simple application that opens the following window:

That it is a prototype only means that it is a program that is not doing anything. The buttons have no function, but it can be a good place to start the development of a program to clarify what it’s all about. First, it is relatively quickly to develop such a program, and partly to the prototype can be presented to the future users, where it can be a useful tool to clarify that the task is understood correct. In this case it is decided, that the program should be able to work with 20 variables, that the program must have an input field for entering an expression and a list box for the results.

145

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

AN EXPRESSION

Exactly an expression can be described with the following syntax diagrams:

146

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

An argument can start with one or more sign characters (plus or minus). Then there are four options 1. const, that always must be a non-negative number – a string that can be converted to a double 2. var, that is a variable and then a string at format Xn, where n is an index 3. function, that is a mathematical function 4. an expression in parentheses What remains is to define what a function is, and it appears from the above. The value of an expression must always be a double.

American online LIGS University is currently enrolling in the Interactive Online BBA, MBA, MSc, DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and ▶▶ save up to 16% on the tuition! ▶▶ pay in 10 installments / 2 years ▶▶ Interactive Online education ▶▶ visit www.ligsuniversity.com to find out more!

Note: LIGS University is not accredited by any nationally recognized accrediting agency listed by the US Secretary of Education. More info here.

147

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

8.2 DESIGN An expression must be represented by a class named Expression. In principle, it is a very simple class, that in addition to a constructor simply consists of a single method that returns from arguments the expression’s value:

Here it is the constructor, that is complex since, as parameter it has the expression as a string, and it is accordingly the constructor’s task to split the string up into tokens and validate whether these tokens represents a legal expression. A token is an item that can be included in an expression, and a token is a substring such as cos, + and a number. According to the above syntax diagrams and associated comments there are following tokens +

addition or sign

-

subtraction or sign

*

multiplication

/

division

(

left parenthesis

)

right parenthesis

,

argument separator

sin

sinus

asin

arc sinus

cos

cosinus

acos

arc cosinus

tan

tangens

atan

arc tanges

cot

cotangens

acot

arc cotangens

ln

natural logarithm

exp

exponential function

log

logarithm 10

alog

antilog

sqr

square function

sqrt

square root

pow

power of

root

root of

abs

absolut value

frac

fraction

floor

interger part

pi

the constant pi

e

the constant e

xn

a variable that start with x and is follwed en non-negative integer

num

a number that is a non-negative decimal number with . as decimal point

148

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

This can result in 30 different tokens – and indeed 31 as plus or minus especially can be a sign. The different tokens has to be treated different, but can be arranged into groups with common properties, and as such, I will define the following class hierarchy, where each token is defined by a class:

149

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

It is very simple classes, and as an example is SinToken a class that represents a sine function. The class is derived from FuncToken, and the class has only two properties, where the first returns the number of arguments, while the second determines the function’s value from a single argument:

The constructor in the class Expression must perform three operations: -- Scanning the expression which means that the string should be split into the tokens that the expression consists of. -- Parsing the expression that means to control that the expression’s syntax is correct according to the syntax diagrams. -- Converting the expression to postfix form, meaning that the expression’s elements must be reorganized into a sequence of tokens in postfix form.

150

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Final FInal example example

To solve the first problem, the parameter string is divided into tokens of the kind defined above. When the string is divided you have a number of tokens, each of which is a string, and all these strings must be converted to a Token object. After the scanning, you have a list of tokens, and parsing has to investigate whether this list of tokens is in accordance with the syntax rules. It is not simple, but it means to write a method corresponding to each of the above syntax diagrams. A STACK

In the book Java 1 I described an ArrayList as an example on a collection class, and I have used an ArrayList many times since. In the first chapter in this book I mentioned the program stack as a data structure, where the runtime system store parameters and local variables. Java also implements a collection class as a stack, and I need that class in the following, and therefore little about what a stack is. It is as an ArrayList a container, that can store objects of a particular type of, but it is a very simple data structure with only two importen operations: 1. 1. push that put an object on the stack (store a value at the top of the stack) 2. 2. pop that returns an remove the object on the top of the stack It is as such a LIFO data structure, where the object that is removed from a stack is the last object, that is put on the stack. In Java a stack also has other operation, and as an exampel and operation peek, that returns the object on the top of the stack but without remove it. It means that peek only look at the top of the stack. As an ArrayList there is no limit om then number of objects a stack can contains. In Java the type is called Stack, and I uses the type in the program, bul I vil also refer to a stack below, and therefore this remark. TO POSTFIX

Usually you write an expression on infix form which means that you writes the operator between two operands, as for example: 2+3

151 151

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

FInal Final example example FInal example

which which means means the the sum sum of of 2 and 3. 3. If If there there are are several several operators, operators, we we need need rules rules for for how how the the which means the sum of 22 and and 3. If there are several operators, we need rules for how the expression must must be be evaluated. evaluated. For For example example means means expression must be evaluated. For example means 2 2*3 3+4 4

that you you first first calculate calculate the the product product of of 2 and 3 and then then adds adds this this result result to to 4 the result result that that you first calculate the product of 22 and and 33 and and then adds this result to 44 – –– the the result 10. In In contrast, contrast, means means isis 10. In contrast, means 2 2+3 3*4 4

that you you first first calculates calculates the the product product of of 3 and 4, 4, since since multiplication multiplication has has higher higher precedence precedence that you first calculates the product of 33 and and 4, since multiplication has higher precedence than addition addition – the result result is therefore 14. 14. If If you you wish wish to to suppress suppress this this rule, rule, you you has has to to than than addition –– the the result isis therefore therefore 14. If you wish to suppress this rule, you has to use parentheses: parentheses: use

and the the expression expression has has the the value value of of 20. 20. and the expression has the value of 20.

(2+3) (2+3) * 4 4

If in in an an expression expression there there are are several several operators operators of of equal equal priority, priority, the the rule rule is that the the operators operators If If in an expression there are several operators of equal priority, the rule isis that that the operators are evaluated evaluated from from left. left. Below Below is first computed computed the the sum sum of of 2 and 3 and then then subtract subtract 4 are evaluated from left. Below isis first first computed the sum of 22 and and 33 and and then subtract 44 because addition addition and and subtraction subtraction have have the the same same priority: priority: because 2+3−4 2+3−4

An expression expression may may be be more more complex, complex, for for example example An An expression may be more complex, for example (1+2 (1+2 ** (3+4))(⁄(5+6) (3+4))(⁄(5+6) ** 7) 7)

where there there are are parentheses parentheses within within the the parentheses. parentheses. The The value value of of the the expression expression is 0.194805. where there are parentheses within the parentheses. The value of the expression isis 0.194805. 0.194805. When an an expression expression contains contains parentheses, parentheses, the the parentheses parentheses are are evaluated evaluated first, first, starting starting with with When an expression contains parentheses, the parentheses are evaluated first, starting with the innermost innermost parentheses. parentheses. It It is certainly possible possible to to write write aaa method method that that does does it, it, but but if the the the innermost parentheses. It isis certainly certainly possible to write method that does it, but ifif the the expression becomes becomes more more complex complex with with mathematical mathematical functions functions and and many many parentheses, parentheses, itit expression not simple, simple, and and therefore therefore one one will will typically typically convert convert the the expression expression to to postfix postfix form. form. This This isis not means that that an an operator operator isis written written after after the the operands. operands. Thus, Thus, the the above above expression’s expression’s isis written written as as means 2 23 3+ + 2 2 3 ** 4 4+ + 234*+ + 23+4* 2 23 3+ +4 4– – 1234+*+56+7*/ 152 152 152

JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA

Finalexample example FInal

forexample exampleyou youmust mustcalculate calculatethe thevalue value, ,you youhave havea alist listofoffive fivetokens, tokens,and andyou youevaluates evaluates IfIffor theexpression expressionby bytraversing traversingthe thelist listfrom fromleft lefttotoright, right,and andevery everytime timeyou youencounters encountersan an the operatorititacts actson onthe thetwo twooperands operandspreceding: preceding: operator 23*4+ 64+ 10

The Theidea ideaisisthat thatany anyexpression expressioncan canbebewritten writtenininpostfix postfixform formwithout withoutusing usingofofparentheses. parentheses. When Whenthe theexpression expressionshould shouldbebeevaluated, evaluated,ititisistraversed traversedjust justfrom fromleft lefttotoright. right.Every Everytime time you come to an operand, put it on a stack. Is it an operator you pop the stack twice you come to an operand, put it on a stack. Is it an operator you pop the stack twice(if(if ititisisan anoperator operatorwith withtwo twoarguments) arguments)calculates calculatesthe theresult resultand andput putititon onthe thestack. stack.Finally Finally the thestack stackwill willcontain containonly onlyone oneelement elementwhich whichisisthe theresult. result.The Themethod methodmay maybased basedon onthe the last lastofofthe theabove aboveexpressions expressionsbebeisisillustrated illustratedininthe thefollowing followingmanner: manner:

11 11

22 11 22

33 22 11 33

44 33 22 11 44

77 22 11 ++

14 14 11 **

15 15 ++

55 15 15 55

66 55 15 15 66

11 11 15 15 ++

77 11 11 15 15 77

77 77 15 0.1948 15 0.1948 // **

.

153 153

JAVA PROGRAMMING JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING

Finalexample example FInal

The is much much easier easier to to evaluate evaluate an anexpression expressionininpostfix postfixform formthan thanone one The conclusion is that it is in therefore worthwhile worthwhile to to seek seekaastrategy strategy(an (analgorithm) algorithm)totoconvert convertanan in infix form and it is therefore expression postfix form. form. ItIt may may be be done done inin the thefollowing followingmanner mannerbybyusing using expression from infix to postfix aa stack: stack: the expresseion is traversed from left and for every tooken 1. if it is a sign push it on the stack 2. if it is a function push it on the stack 3. if it is a variable push it on the stack 4. if it is a number push it on the stack 5. if it is a left parenthes push it on the stack 6. if it is a right parenthes, then pop the stack and add the top of the stack to the resultat until you get a left parenthes 7. if it is an operator then pop the stack and add the top of the stack to the resultat as long as the priority of the top of the stack is less than or equal to the priority of the element, push the element on the stack pop the stack and add the top of stack to the result until the stack is empty

As it is is crucial crucial in in the the algorithm algorithm that that there thereare areassigned assignedthe theright rightpriorities prioritiesfor for As you you can can see, see, it the tokens. It It is is the the priorities priorities that that determine determine when whentotomove movefrom fromthe thestack stacktoto the individual individual tokens. the is just just aa list. list. The The two two important important points pointsininthe thealgorithm algorithmare are66and and7.7.IfIf the result, result, which which is you for example example aa multiplication multiplication––you youmust mustfirst firstmove moveeverything everythingonon you get get to to an an operator operator –– for the better priority priority than than multiplication multiplication toto the the result resultlist. list.ItItwill willbebenumbers, numbers, the stack stack with with aa better variables and then then the the multiplication multiplication operator operatorisisput puton onthe thestack. stack. variables and and functions, functions, and

So, tokens are are converted convertedto topostfix postfixform, form,ititisissimple simpletotoimplement implementmethod method So, if if the the expression’s expression’s tokens getValue() class Expression. Expression. So, So, ifif the the expression's expression's tokens tokens are are converted convertedtotopostfix postfixform, form,it itis issimple simpletotoimpl im getValue() in in the the class getValue() getValue()in inthe theclass classExpression. Expression.

If the expression expression If you you look look at at the

If If you you look lookatatthe theexpression expression

(1 + 2 * (3 + 4) )⁄( (5 + 6) * 7)

(1 (1++22∗∗(3(3++4)4))⁄)(⁄(5 ( (5++6)6)∗ ∗7)7)

can be be converted converted to in the manner: can totopostfix form itit can to postfix postfixititform form the following following manner: can be beinconverted converted postfix formininthe thefollowing followingmanner: manner: 11 11 11 1 1 1 1 1 1 1 1 1 1 1 1

22 22 2 2 2 2 2 2 2 2 2 2 2 2

( ((

33 3 3 3 3 3 3 3 3 3 3 3 3

4 4 4 4 4 4 4 4 4 4 4 4

+ + + + + + + + + + + +

1 (1 1( 1

* * * * * * * * * *

+ + + 5 + 5 + 5 6 + + 5 6 + + 5 6 + 7 * + 5 6 + 7 + 5 6 + 7 ** / + 5 6 + 7 * /

+ (+ 154 +( +

154

2 +2 (+ 2( 2

* +* (+ ( *

( ( * * + (+ (( (

3 (3 ( * * + (+ 3( 3

+ (+ ( * * + (+ +( +

4 +4 (+ ( * * + (+ 4( 4

* +* ( + ) ( )

)

)

1 1 1 1 JAVA 1 3: 1 1

2 3 2 3 4 + 2 3 4 + * + 2 3 4 + * + 5 2 3 4 + * + 5 6 + OBJECT-ORIENTED PROGRAMMING 2 3 4 + * + 5 6 + 7 * 2 3 4 + * + 5 6 + 7 * /

( (

( / (

1 ( 1

+ ( +

2 + ( 2

( ( / (

5 ( ( / 5

+ ( ( / +

* + ( * 6 + ( ( / 6

Final example

( * + ( (

( / )

3 ( * + ( 3

+ ( * + ( +

4 + ( * + ( 4

* ( /

7 * ( / 7

/ )

*

* + ( )

)

/ /

In this particular task, I will apply the following priorities: --------

numbers, variables 0 sign 1 function 2 multiplication, division 3 addition, subtraction 4 left parenthes 9 right parenthes, comma 99

8.3 PROGRAMMING As is apparent from the above, the program will consist of many classes corresponding to the token classes. They are all in the same file, named Tokens that contain a single public class. It has a single static method called toToken() which, based on a substring representing the next token, and a Token object for the last token converts the substring to a token. The class is used by the Expression class as part of the scanning. The class Expression is as mentioned, a complex class and after the scanning the class has a list of Token objects. These objects must be parsed to test the syntax of the expression, and for this purpose must be written a number of methods corresponding to the syntax diagrams. This methods uses recursion which I will mention below. After the parsing, the list of tokens must be converted to postfix form, but with the above algorithm it is relatively simple. You should note, that the conversion needs a stack, that is a collection class as explained above. The same applies to implements the method getValue(), that calculates the value of an expression.

155

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final FInal example

RECURSION

To write the class Expression (the syntax checker) I needs recursion and therefore a few words about what it is. A method in a class can be seen as an isolated code that performs a specific operation on basis of parameters and possible returns a value. The method’s statements, the commands it executes, can be all possible statements and there are no limitations on what it can be. For example calling another method, and a method may thus especially also calls the method itself. If so, wee say that the method is recursive. As an example of a recursive method – and a method which does not concern the specific program – is shown a method that determines the factorial of n: static long factorial(int n) { if (n == 0 || n == 1) return 1; return n * factorial(n – 1); }

Join the best at the Maastricht University School of Business and Economics!

Top master’s programmes • 3  3rd place Financial Times worldwide ranking: MSc International Business • 1st place: MSc International Business • 1st place: MSc Financial Economics • 2nd place: MSc Management of Learning • 2nd place: MSc Economics • 2nd place: MSc Econometrics and Operations Research • 2nd place: MSc Global Supply Chain Management and Change Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012; Financial Times Global Masters in Management ranking 2012

Visit us and find out why we are the best! Master’s Open Day: 22 February 2014

Maastricht University is the best specialist university in the Netherlands (Elsevier)

www.mastersopenday.nl

156

method, and a method may thus especially also calls the method itself. If so, wee say that the method is recursive. As an example of a recursive method - and a method which does not concern the specific program - is shown a method that determines the factorial of n:

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

static long factorial(int n) { Atifa first methods (n ==glance, 0 || nrecursive == 1) return 1; can be hard to figure out, but once you returnwith n * the factorial(n familiar principle, -it 1); is not particularly difficult. Above is the principle }

have been that if n is 0 or 1, you can directly determine the result. If n is greater than 1, one can determine the factorial of n as n times the factorial of n-1. You can think of it in this way, to determine At a first glance, recursive methods can be hard to figure out, but once you have been familiar with the the factorial of n it is reduced to determine the factorial of n-1, which is a smaller a problem principle, it is not particularly difficult. Above is the principle that if n is 0 or 1, you can directly than I started with:If To factorial of n. If the I repeat above a sufficient determine the result. n isdetermine greater thanthe 1, one can determine factorial of n as n times thenumber factorial of n-1. times, I get finally to the simple case in which n is 0 or 1 and where I can directly You can think of it in this way, to determine the factorial of n it is reduced to determine the determine the result. factorial of n-1, which is a smaller a problem than I started with: To determine the factorial of n. If I repeat above a sufficient number of times, I get finally to the simple case in which n is 0 or 1 and whereprinciple I can directly result. is that a problem may be divided into two problems: The of a determine recursivethe method

A simple problem which can readily be solved, and a simpler (smaller) problem of the same The principle of a recursive method is that a problem may be divided into two problems: A simple kind as the original. problem which can readily be solved, and a simpler (smaller) problem of the same kind as the original.

Formally, thefactorial factorial is defined as follows: Formally, the of nofisndefined as follows: 1 𝑓𝑓𝑓𝑓𝑓𝑓 𝑛𝑛 = 0 or 𝑛𝑛 = 1 𝑛𝑛! = { } 𝑛𝑛 ⋅ (𝑛𝑛 − 1)! 𝑓𝑓𝑓𝑓𝑓𝑓 𝑛𝑛 > 1

and then by a recursive definition, and in such 106situations, recursion is often a good solution. In this case, the method factorial() simply just a rewrite of the mathematical formula to a method in Java. It is clear that in this case the method could be written iteratively by means of a simple loop, and this solution would even be preferable, but in other situations, recursion is a good solution to provide a simple solutions and even a code which is easier to read and understand than an equivalent iterative solution. There is reason to always be aware of recursive methods, as each recursive call creates an activation block on the program stack. There is therefore a danger that the recursive methods use the whole stack, with the result that the program will crash. THE VIEW

This leaves the program’s view, which simply consists of a single class named MainView. The class contains nothing new and should not be discussed further here.

157

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Final example

The program Calc has in contrast to the programs that I have shown so far in this series of books on software development, focus on algorithms, and thus how to solve a relatively complex problem using a program. Rather than show the code here (and there are over 1200 lines of code) should you study the code and its algorithms and here especially -----

how how how how

the scan is done the expression is parsed an expression is converted to postfix an expression evaluated

It happens all in class Expression, but the code is carefully documented.

158

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A

APPENDIX A Applications must be tested before they can be used, and for example you can try out the program, and check whether the program gives the correct result. It will always be a part of a test, since it is here that one realizes where the program to the user works as it should. You must remember to test how the application behaves when you enter something illegal or the program use arguments that are not legal, and such, and it is also important to test what happens when the window is resized. Besides, it is important that such user tests are performed by others than who wrote the program when there is a great risk that the programmer because of complicity overlook anything: You never know what real users can find on! Sometimes you can not do anything other than what I have mentioned above, but in other contexts it is necessary to test the code on a lower level, where the programmer tests the code. I will mention three important ways: 1. Comment the code. 2. Debug the code. 3. Unit test the code. and I will as an example use the program CurrrencyProgram.

COMMENT THE CODE All three methods are important, but each with their opportunities. I have previously mentioned that to write comment’s in the code as an effective (and often overlooked) means to ensure the quality of the finished program. In principle, it is trivial, but you should not underestimate the process. For the sake of future maintenance is good documentation clearly important, but more important is the process of writing the documentation, if it does otherwise performed conscientiously. I think you have to document the following: -- In front of each class write a comment that tells of the class’s purpose and its genesis, but generally you should write everything that you believe that that a person that in the future should maintain the code, needs to know. The comment is updated by any subsequent substantial change of the class, and is described as a Java comment, so that it becomes part of a complete class documentation. -- All variables and other data definitions are documentated with a short comment for what a variable is use for. Here I not use Java comments, unless it is a public static variabel or field.

159

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A

-- All public methods are documented with Java comments, so they are included in a part of the final class documentation. All parameters, return values and exceptions are documented, but in general there should also be a description of the method’s purpose and including pre conditions of the parameters and possible side effects. For simple get methods, it is typically sufficient to comment the return value. -- All private and protected methods are in principle documented in the same way, but here I usually do not use Java comments. The documentation of these methods should not be included in the final class documentation. -- Finally, there are algorithms in which it may be necessary to comment on the details of the code. Generally I leave those comments to be part of the comment in front of the method, and to endeavor to avoid comments inside the body of the method, but if it is necessary to explain how the algorithm work, of course not refrain from such comments. As mentioned, the process is important because as a part of the job thinking through why you now have written the code that you have. I would not say that in this way, all errors are found, but you will find an incredible number of inconveniences and places where the solution is ineffective. It is an extensive work documenting code, but the work is well spent! It is not all code, I document with comments and it is typically the controller and model classes. However, it is rare to documents classes in the user interface and at least only to a limited extent. I feel simply not that it makes any special dividends, whether as future documentation or detection of inexpediencies. The reason is probably that the development of the user interface is largely reuse of code from other programs. The project CurrencyProgram is documented according to those recommendations. JAVA DOC

As mentioned above, you should widely use Java comments, and I also discussed how to get NetBeans to insert a skeleton in front of a method. As shown many times there is a special syntax for inserting comments from the parameters, return values, etc.. and there are actually some more, where the most important are: -- @author, the author of the class -- {@code} Display text in code font without interpreting the test as HTML -- @exception Adds a Throws heading to the generated documentation, with the classname and a description.

160

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A

-- @{link} Inserts an inline link with the visible text label that points to the documentation for the specified package, class, or member name of a referenced class. -- @param Adds a parameter with the specified parameter name followed by the specified description of the parameter. -- @return Adds a Returns section with a description. -- @see Adds a See Also heading with a link or text entry that points to a reference. The idea is that by using a tool these comments can generate a complete documentation as an HTML document, and you can even write your own HTML in the docmentation. If you have a project like Currency and in NetBeans right clicks on the project name, you get a menu item Generate Javadoc, which generates the documentation. NetBeans will then open a browser with the the result, which you can save. Below is shown the documentation of the current project:

161

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A

DEBUG THE CODE Now it may not be entirely correct to call debug the code for part of the test, but NetBeans has a good debugger, and since I have not previously referred to it, it must have a few words at this location. When you want to test a program, it will often fail, and perhaps you get a wrong result, or the program crashes. The task then is to find the error and correct it, and here the debugger can help. You can set a breakpoint, which means that the excution of the program stops when the program reaches that point in the code, and you can then see the value of variables and check whether they have the right value. You can also step forward in the code statement by statement and constantly monitor what happens with variables. The debugger is a highly efficient tool to find where a program failed, but in general the debugger is used to analyze the code. As an example, one might think that the program CurrencyProgram fails, when you create a new CurrencyTable object (which is a singleton, and there is a possibility of an error when the object is instantiated), and the task is then to find out where it goes wrong. As an example, one could then set a breakpoint in the method init():

Need help with your dissertation? Get in-depth feedback & advice from experts in your topic area. Find out what you can do to improve the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

162

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A

You set the breakpoint by clicking with the mouse next to the desired line (here line 88). From the menu you can then start the debugger by selecting Debug | Debug Project. When init() is performed, the program will stop, where there is set a breakpoint, and you can then step through the code line by line (by using F8). That way you can see where the program possibly crashes. You can also put a watch on variables (by right-clicking in the debug window), and you can see the variables values and what happens to them:

163

JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Appendix appendIx A a

The The debugger debugger has has many many other other opportunities opportunities to to analyze analyze the the code. code. For For example example you you can can by by pressing pressing F7 F7 jump jump into into the the code code for for aa method. method. You You should should examine examine the the Debug Debug menu menu to to get get an an idea idea of of what what is is possible. possible. It It is is worthwhile worthwhile to to use use some some time time learning learning the the debugger debugger to to know, know, since since itit is is aa highly highly effective effective tool tool for for troubleshooting. troubleshooting. Probably Probably itit is is not not directly directly aa testing testing tool, tool, but but aa good good tool tool for for finding finding the the errors errors detected detected during during the the testing. testing.

UNIT TEST Unit Unit test test is is carried carried out out with with aa tool, tool, that that is is integrated integrated into into NetBeans. NetBeans. Unlike Unlike the the testing testing of of the the program, program, where where you you test test how how the the finished finished program program behaves, behaves, and and whether whether itit meets meets all all requirements, requirements, unit unit test test is is aa systematic systematic way way to to test test individual individual classes classes and and methods, methods, and and therefore therefore itit is is something something that that must must be be done done by by the the programmer programmer as as part part of of the the development. development. It It is is not not everything everything that that you you can can unit unit test, test, and and itit is is best best suited suited for for testing testing controller controller and and model model classes, classes, and and specifically specifically unit unit test test is is effective effective test test of of classes classes in in libraries. libraries. II will will test test the the class class Controller, Controller, which which has has three three methods: methods: package currencyprogram; import java.util.*; import java.io.*; /** * Class containing methods to the program's data processing. */ public class Controller { /** * Converter an amount from one currency to another currency. * The conversion is done primarily through the next calculation method, and this * method should primarily validate that amount is a legal number. * @param amount The amount to be converted * @param from The currency to be converted from * @param to The currency to be converted to * @return The result of the conversion * @throws Exception The amount can not be parsed or an currency objects is null */ public double calculate(String amount, Currency from, Currency to) throws Exception { … }

164 164

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A appendIx a

/** * Converter an amount from one currency to another currency. * @param amount The amount to be converted * @param from The currency to be converted from * @param to The currency to be converted to * @return The result of the conversion * @throws Exception If one of the two currency objects are null */ public double calculate(double amount, Currency from, Currency to) throws Exception { … } /** * Updating the currency table from a semicolon delimited text file. * Each line consists of three fields separated by semicolons and in the * following order: * name;code;rate * @param file The file from which to read currencies * @return A list containing all lines that could not be converted into currency */

Brain power

By 2020, wind could provide one-tenth of our planet’s electricity needs. Already today, SKF’s innovative knowhow is crucial to running a large proportion of the world’s wind turbines. Up to 25 % of the generating costs relate to maintenance. These can be reduced dramatically thanks to our systems for on-line condition monitoring and automatic lubrication. We help make it more economical to create cleaner, cheaper energy out of thin air. By sharing our experience, expertise, and creativity, industries can boost performance beyond expectations. Therefore we need the best employees who can meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering. Visit us at www.skf.com/knowledge

165 165

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Appendix A appendIx a

public ArrayList<String> update(File file) { … }

First, First,I Icreates createsaatest testclass. class.You Youdo dothis thisby byright-clicking right-clickingon onthe theclass classname nameController.java Controller.java ininthe Projects tab, and here should you choose Tools | Create / Update Tests the Projects tab, and here should you choose Tools | Create / Update Tests

I Ikept keptall allthe thesettings settingsasasthey theyare. are.When Whenyou youclick clickOK, OK,you youmay mayreceive receiveaadialog dialogbox: box:

166 166

JAVA3:3:OBJECT-ORIENTED OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA

appendIxAa Appendix

andififso, so,choose chooseJUnit JUnit4.4.Then ThenNetBeans NetBeanscreates createsaatest testclass, class,asasshown shownbelow. below.The Thetest testclass class and calledControllerTest, ControllerTest,and andbesides besidesaadefault defaultconstructor constructorisiscreated createdfour fourempty emptymethods methods isiscalled well asas three three test test methods. methods. There There are are generally generally created created aa test test method method for for each each nonnonasas well privatemethod methodininthe theclass. class.When Whenthe thetest testclass classisiscarried carriedout, out,this thismeans meansthat thatall allofofthe the private testmethods methodsare areexecuted. executed.The Thefour fourempty emptymethods methodsare areused usedtotoadd addcode codethat thatyou youwant want test performed,respectively respectivelybefore beforeand andafter afterthe thetest, test,and andtwo twomethods methodstotobe beperformed performedbefore before performed, andafter afterthe theindividual individualtest testmethods. methods.InInthis thiscase caseI Iwill willnot notadd addanything anythingand andthe themethods methods and couldeasily easilybe bedeleted. deleted. could package currencyprogram; import import import import import import import import public

java.io.File; java.util.ArrayList; org.junit.After; org.junit.AfterClass; org.junit.Before; org.junit.BeforeClass; org.junit.Test; static org.junit.Assert.*; class ControllerTest {

public ControllerTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testCalculate_3args_1() throws Exception { System.out.println("calculate"); String amount = ""; Currency from = null;

167 167

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

Appendix A appendIx a

Currency to = null; Controller instance = new Controller(); double expResult = 0.0; double result = instance.calculate(amount, from, to); assertEquals(expResult, result, 0.0); fail("The test case is a prototype.");

@Test public void testCalculate_3args_2() throws Exception { System.out.println("calculate"); double amount = 0.0; Currency from = null; Currency to = null; Controller instance = new Controller(); double expResult = 0.0; double result = instance.calculate(amount, from, to); assertEquals(expResult, result, 0.0); fail("The test case is a prototype."); }

168 168

JAVA 3: OBJECT-ORIENTED PROGRAMMING

appendIx a

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING @Test

Appendix A appendIx a

public void testUpdate() { System.out.println("update"); @Test File file null; public void= testUpdate() { Controller instance = new Controller(); System.out.println("update"); ArrayList<String> File file = null; expResult = null; ArrayList<String> instance.update(file); Controller instanceresult = new =Controller(); assertEquals(expResult, result); ArrayList<String> expResult = null; fail("The test case is a =prototype."); ArrayList<String> result instance.update(file); }assertEquals(expResult, result);

}}

fail("The test case is a prototype.");

} You must specifically noting how the test methods are named, and how to solve the problem

that two methods has the same name. The auto-generated test methods can usually not You mustdirectly specifically howbut the you test methods arethat named, how toincludes solve theusual problem be used for noting anything, can notice the and methods Java that two methods theofsame name. testtomethods can usually not statements, and thehas work writing unitThe testsauto-generated is to write code test methods. As a start, be usedchanged directly the for middle anything, you can notice that the methods usual I have testbut method to the following while I haveincludes comment out Java the statements, work of writing unit tests is to write code to test methods. As a start, code in the and otherthetwo: I have changed the middle test method to the following while I have comment out the @Testin the other two: code public void testCalculate_3args_2() throws Exception { System.out.println("calculate(double amount, Currency from, Currency to)"); @Test Currency = new Currency("DKK", "Danish crowns", 100); public voidc1testCalculate_3args_2() throws Exception { Currency c2 = new Currency("EUR", "Euro", System.out.println("calculate(double amount,750); Currency from, Currency to)"); Currency c1 c3 == new new Currency("DKK", Currency("USD", "Danish "US dollar", 600); Currency crowns", 100); Controller instance = new Controller(); Currency c2 = new Currency("EUR", "Euro", 750); assertEquals(instance.calculate(1000, c1), 7500, Currency c3 = new Currency("USD", "US c2, dollar", 600); 0.0001); assertEquals(instance.calculate(1000, c1, c2), 133.33, 0.01); Controller instance = new Controller(); assertEquals(instance.calculate(1000, c2, c2, c1), c3), 7500, 1200, 0.0001); 0.0001); assertEquals(instance.calculate(1000, assertEquals(instance.calculate(1000, c3, c2), 800, 0.0001); assertEquals(instance.calculate(1000, c1, c2), 133.33, 0.01); }assertEquals(instance.calculate(1000, c2, c3), 1200, 0.0001); assertEquals(instance.calculate(1000, c3, c2), 800, 0.0001);

} Wee say that the method has four test cases. Each test case performs the method assertEquals()

with two currency objects as parameters. Every time the method’s return value is tested whether Wee thevalue method four test test case the the method assertEquals() it hassay a that certain andhas because thecases. typeEach is double, youperforms must with last parameter set with two currency objects asIfparameters. timetest the is method’s returnwith valueanis tested whether the maximum deviation. a test case Every fails, the interrupted error message. it has isa to certain value is double, you must with error. the lastThat’s parameter set That accept the and test because all tests the casestype must be performed without what the the deviation. a test casetofails, is interrupted an error message. unitmaximum test is about, and theIfonly thing learntheis test which test cases it with is possible to write. To That is tothe accept test all the teststest cases must be performed That’s the perform test, the right-click class under the Projectswithout tab anderror. choose Test what File. The unit about,the andtest theisonly thing tocorrectly: learn is which test cases it is possible to write. To resulttest saysis where performed perform the test, right-click the test class under the Projects tab and choose Test File. The result says where the test is performed correctly:

169 169 169

JAVA 3:3:OBJECT-ORIENTED JAVA OBJECT-ORIENTEDPROGRAMMING PROGRAMMING JAVA JAVA 3: 3: OBJECT-ORIENTED OBJECT-ORIENTED PROGRAMMING PROGRAMMING

Appendix Aa appendIx appendIx appendIx a a

InIn this case, the test failed. The reason that the third test case fails, since erroneously Inthis thiscase, case,the thetest testfailed. failed.The Thereason reasonisis isthat thatthe thethird thirdtest testcase casefails, fails,since since–– –erroneously erroneously–– – there is an incorrect expected value. I change it to there is an incorrect expected value. I change it to there is an incorrect expected value. I change it to assertEquals(instance.calculate(1000, assertEquals(instance.calculate(1000, v2, v3), 1250, 0.0001); assertEquals(instance.calculate(1000, v2, v2, v3), v3), 1250, 1250, 0.0001); 0.0001);

and and the test performed correct: andthe thetest testisis isperformed performedcorrect: correct:

The The value such tests course determined by the number test cases. Below the Thevalue valueofof ofsuch suchtests testsisis isofof ofcourse coursedetermined determinedby bythe thenumber numberofof oftest testcases. cases.Below Belowisis isthe the code for the first test method: code for the first test method: code for the first test method: @Test @Test @Test public public void testCalculate_3args_1() throws Exception { public void void testCalculate_3args_1() testCalculate_3args_1() throws throws Exception Exception { { System.out.println("calculate(String amount, Currency from, Currency to)"); System.out.println("calculate(String amount, Currency System.out.println("calculate(String amount, Currency from, from, Currency Currency to)"); to)"); Currency c1 = new Currency("DKK", "Danish crowns", 100); Currency c1 = new Currency("DKK", "Danish crowns", 100); Currency c1 = new Currency("DKK", "Danish crowns", 100); Currency c2 = new Currency("EUR", "Euro", 750); Currency Currency c2 c2 = = new new Currency("EUR", Currency("EUR", "Euro", "Euro", 750); 750); Currency c3 = new Currency("USD", "US dollar", Currency c3 = new Currency("USD", "US dollar", 600); Currency c3 = new Currency("USD", "US dollar", 600); 600); Controller instance = new Controller(); Controller instance = new Controller(); Controller instance = new Controller(); assertTrue(Math.abs(instance.calculate("1000", assertTrue(Math.abs(instance.calculate("1000", c2, c1) – 7500) < 0.01); assertTrue(Math.abs(instance.calculate("1000", c2, c2, c1) c1) – – 7500) 7500) < < 0.01); 0.01); assertTrue(Math.abs(instance.calculate("1000", c1, c2) – 133.33) < 0.01); assertTrue(Math.abs(instance.calculate("1000", c1, c2) – 133.33) < assertTrue(Math.abs(instance.calculate("1000", c1, c2) – 133.33) < 0.01); 0.01); assertTrue(Math.abs(instance.calculate("1000", c2, c3) – 1250) < 0.01); assertTrue(Math.abs(instance.calculate("1000", c2, c3) – 1250) < 0.01); assertTrue(Math.abs(instance.calculate("1000", c2, c3) – 1250) < 0.01); assertTrue(Math.abs(instance.calculate("1000", c3, c2) – 800) < 0.01); assertTrue(Math.abs(instance.calculate("1000", assertTrue(Math.abs(instance.calculate("1000", c3, c3, c2) c2) – – 800) 800) < < 0.01); 0.01); } } }

ItItlooks like the previous test method, and the difference between the two methods is also It looks looks like like the the previous previous test test method, method, and and the the difference difference between between the the two two methods methods is is also also only the type ofofthe first parameter. Each test case isiswritten this time ininaadifferent manner only the type the first parameter. Each test case written this time different manner only the type of the first parameter. Each test case is written this time in a different manner by means ofofassertTrue(). There are no special reasons for it ininaddition to showing the syntax. by by means means of assertTrue(). assertTrue(). There There are are no no special special reasons reasons for for it it in addition addition to to showing showing the the syntax. syntax. You can also add your own test methods, and the following method isisused to test whether You You can can also also add add your your own own test test methods, methods, and and the the following following method method is used used to to test test whether whether you get an exception ififthe calculate() method isisperformed with aaCurrency that isisnull: you get an exception the calculate() method performed with Currency that you get an exception if the calculate() method is performed with a Currency that is null: null: @Test(expected=Exception.class) @Test(expected=Exception.class) @Test(expected=Exception.class) public public void testNullValuta() throws Exception { public void void testNullValuta() testNullValuta() throws throws Exception Exception { { System.out.println("calculate with arguments that is null"); System.out.println("calculate with arguments that System.out.println("calculate with arguments that is is null"); null"); Currency c1 = new Currency("DKK", "Danish crowns", 100); Currency c1 = new Currency("DKK", "Danish crowns", 100); Currency c1 = new Currency("DKK", "Danish crowns", 100); Controller instance = new Controller(); Controller Controller instance instance = = new new Controller(); Controller();

170 170 170 170

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

} }

Appendix A appendIx a appendIx a

assertEquals(instance.calculate(1000, assertEquals(instance.calculate(1000, assertEquals(instance.calculate(1000, assertEquals(instance.calculate(1000,

c1, null), c1, null), null, c1), null, c1),

7500, 0.0001); 7500, 0.0001); 133.33, 0.01); 133.33, 0.01);

You You should should note, note, how how to to specify specify that that aa test test case case may may raise raise an an exception. exception. Next Next II adds adds aa test test class class for for the the class class CurrencyTable. CurrencyTable. This This is is done done in in exactly exactly the the same same manner manner as above, and the results are as follows: as above, and the results are as follows: package currencyprogram; package currencyprogram; import import import import import import import import import import import import import import public public

java.util.Iterator; java.util.Iterator; org.junit.After; org.junit.After; org.junit.AfterClass; org.junit.AfterClass; org.junit.Before; org.junit.Before; org.junit.BeforeClass; org.junit.BeforeClass; org.junit.Test; org.junit.Test; static org.junit.Assert.*; static org.junit.Assert.*; class CurrencyTableTest { class CurrencyTableTest {

public CurrencyTableTest() { public CurrencyTableTest() { } }

171 171 171

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A appendIx a

@BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testGetInstance() { System.out.println("getInstance"); CurrencyTable expResult = null; CurrencyTable result = CurrencyTable.getInstance(); assertEquals(expResult, result); fail("The test case is a prototype."); } @Test public void testGetCurrency() throws Exception { System.out.println("getCurrency"); String code = ""; CurrencyTable instance = null; Currency expResult = null; Currency result = instance.getCurrency(code); assertEquals(expResult, result); fail("The test case is a prototype."); } @Test public void testIterator() { System.out.println("iterator"); CurrencyTable instance = null; Iterator expResult = null; Iterator result = instance.iterator(); assertEquals(expResult, result); fail("The test case is a prototype."); } @Test public void testUpdate() { System.out.println("update");

172 172

JAVA 3: OBJECT-ORIENTED PROGRAMMING JAVA 3: OBJECT-ORIENTED PROGRAMMING

}

}

Appendix A appendIx a

Currency currency = null; CurrencyTable instance = null; boolean expResult = false; boolean result = instance.update(currency); assertEquals(expResult, result); fail("The test case is a prototype.");

Thistime timethere thereare arefour fourtest testmethods. methods.The Thefirst firsttest testthe thestatic staticmethod methodgetInstance(), getInstance(),which which This simplyreturns returnsaareference referencetotothe thesingleton. singleton.ItItmakes makesno nosense, sense,and andI Iwill willdelete deleteit.it.So Soyou you simply cansimply simplydelete deletethe thetest testmethods methodswhich whichyou youdo donot notwish wishtotomake makeuse useof. of.I Iwould wouldalso also can deletethe thetest testmethod methodthat thattests teststhe theiterator. iterator.I Iwill willnow’s now’swriting writingthe thecode codefor forthe thelast lasttwo two delete testmethods: methods: test @Test public void testGetCurrency() throws Exception { System.out.println("getCurrency(String code)"); assertNotNull(CurrencyTable.getInstance().getCurrency("DKK")); assertNotNull(CurrencyTable.getInstance().getCurrency("EUR")); } @Test public void testUpdate() { System.out.println("update(Currency currency)"); try { int count1 = 0; for (Currency c : CurrencyTable.getInstance()) ++count1; Currency c1 = new Currency("EUR", "European euro", 800); Currency c2 = new Currency("TST", "Test currency", 1000); CurrencyTable.getInstance().update(c1); CurrencyTable.getInstance().update(c2); Currency c3 = CurrencyTable.getInstance().getCurrency("EUR"); Currency c4 = CurrencyTable.getInstance().getCurrency("TST"); int count2 = 0; for (Currency c : CurrencyTable.getInstance()) ++count2; System.out.println(c3.getName()); System.out.println(c4.getName()); assertEquals(c3.getRate(), 800, 0.0001); assertEquals(c4.getRate(), 1000, 0.0001); assertEquals(count2 – count1, 1); } catch (Exception ex) { System.out.println(ex); } }

173 173

JAVA 3: OBJECT-ORIENTED PROGRAMMING

Appendix A

There is not much to explain, but note that the first use assertNotNull() to test that an object is not null. Note also that this time you should not create an instance of the CurrencyTable, as the class is written as a singleton. Finally, note the last test method, and that a test method can include all the Java statements that may be needed. Back there is a test method in the test class ControllerTest, but I will not write the code, but note that it is simple to write a file with test data and test if the method is working properly. The strength of a unit test depends as mentioned by the number of test cases. It can be a lot of work to write test classes for unit testing, but classes must be tested, and the real value of the unit test is that if first written individual test methods you can repeat the test all the times that may be required, and it is, in principle, every time the class is modified. As a final note regarding unit test NetBeans has a menu Run | Test Project, and if you choose that, all test classes are performed.

Challenge the way we run

EXPERIENCE THE POWER OF FULL ENGAGEMENT… RUN FASTER. RUN LONGER.. RUN EASIER…

READ MORE & PRE-ORDER TODAY WWW.GAITEYE.COM

1349906_A6_4+0.indd 1

22-08-2014 12:56:57

174

More Documents from "sufyan maher"

Waqtkasafar In Urdu.pdf
December 2019 13
Innocent-human.pdf
December 2019 36
Ekapoq.docx
June 2020 14
August 2019 28
Asbab_al_wurud.pdf
May 2020 12