001-2023-0713_DLBCSOOPJ01_Course_Book (5).pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

OBJECT-ORIENTED PROGRAMMING WITH JAVA DLBCSOOPJ01 OBJECT-ORIENTED PROGRAMMING WITH JAVA MASTHEAD Publisher: IU Internationale Hochschule GmbH IU International University of Applied Sciences Juri-Gagarin-Ring 152 D-99084 Erfurt Mailing address: Albert-Proeller-Str...

OBJECT-ORIENTED PROGRAMMING WITH JAVA DLBCSOOPJ01 OBJECT-ORIENTED PROGRAMMING WITH JAVA MASTHEAD Publisher: IU Internationale Hochschule GmbH IU International University of Applied Sciences Juri-Gagarin-Ring 152 D-99084 Erfurt Mailing address: Albert-Proeller-Straße 15-19 D-86675 Buchdorf [email protected] www.iu.de DLBCSOOPJ01 Version No.: 001-2023-0713 N. N. © 2023 IU Internationale Hochschule GmbH This course book is protected by copyright. All rights reserved. This course book may not be reproduced and/or electronically edited, duplicated, or dis- tributed in any kind of form without written permission by the IU Internationale Hoch- schule GmbH (hereinafter referred to as IU). The authors/publishers have identified the authors and sources of all graphics to the best of their abilities. However, if any erroneous information has been provided, please notify us accordingly. 2 PROF. DR. DAMIR ISMAILOVIĆ Mr. Ismailović has been a professor of software development at IU International University of Applied Sciences since 2019. His main area of teaching and research is software engineering, and his specializations include software development, project organization and manage- ment, agile methodology, requirements engineering, software architecture and processes, design patterns, usability engineering, mobile engineering, and game engineering. Mr. Ismailović holds a doctoral degree in applied software engineering from the Technical University Munich (Germany), where he focused on software engineering, software develop- ment, mobile technologies, usability engineering, and gamification and serious games. Mr. Ismailović has founded several innovative start-ups. In previous leading positions at sev- eral major German companies, he was responsible for multiple areas—including modern custom software solutions, mobile topics, Industry 4.0 and IoT, and gamification and serious games—and for setting up various competence centers and branches. 3 TABLE OF CONTENTS OBJECT-ORIENTED PROGRAMMING WITH JAVA Module Director.................................................................. 3 Introduction Signposts Throughout the Course Book............................................. 8 Basic Reading.................................................................... 9 Further Reading................................................................. 10 Learning Objectives.............................................................. 12 Unit 1 Introduction to Object-Oriented System Development 13 1.1 Object Orientation as a Way of Looking at Complex Systems..................... 14 1.2 The Object as a Basic Concept of Object Orientation............................. 15 1.3 Phases in the Object-Oriented Development Process............................ 16 1.4 Basic Principle of Object-Oriented System Development......................... 18 Unit 2 Introduction to Object-Oriented Modeling 23 2.1 Structuring Problems With Classes............................................ 24 2.2 Identifying Classes........................................................... 25 2.3 Attributes as Properties of Classes............................................. 27 2.4 Methods as Functions of Classes............................................... 28 2.5 Associations between Classes................................................. 30 2.6 Unified Modeling Language (UML)............................................. 33 Unit 3 Programming Classes in Java 37 3.1 Introduction to the Java Programming Language............................... 38 3.2 Basic Elements of a Class in Java.............................................. 41 3.3 Attributes in Java............................................................ 42 3.4 Methods in Java............................................................. 44 3.5 Main Method: Starting Point of a Java Program................................. 51 4 Unit 4 Java Language Constructs 55 4.1 Primitive Data Types......................................................... 56 4.2 Variables.................................................................... 57 4.3 Operators and Expressions.................................................... 59 4.4 Control Structures........................................................... 64 4.5 Packages and Visibility Modifiers.............................................. 73 Unit 5 Inheritance 77 5.1 Modeling and Inheritance in the Class Diagram................................. 79 5.2 Programming Inheritance in Java.............................................. 83 Unit 6 Important Object-Oriented Concepts 91 6.1 Abstract Classes............................................................. 92 6.2 Polymorphism............................................................... 96 6.3 Static Attributes and Methods................................................. 99 Unit 7 Constructors for Generating Objects 103 7.1 The Standard Constructor................................................... 104 7.2 Overloading Constructors................................................... 107 7.3 Constructors and Inheritance................................................ 112 Unit 8 Handling Exceptions with Exceptions 115 8.1 Typical Scenarios of Exception Handling...................................... 116 8.2 Standard Exceptions in Java................................................. 119 8.3 Defining Your Own Exceptions................................................ 124 Unit 9 Programming Interfaces with Interfaces 129 9.1 Typical Scenarios of Programming Interfaces.................................. 130 9.2 Interfaces as Programming Interfaces in Java.................................. 133 Appendix List of References............................................................... 140 List of Tables and Figures........................................................ 141 5 INTRODUCTION WELCOME SIGNPOSTS THROUGHOUT THE COURSE BOOK This course book contains the core content for this course. Additional learning materials can be found on the learning platform, but this course book should form the basis for your learning. The content of this course book is divided into units, which are divided further into sec- tions. Each section contains only one new key concept to allow you to quickly and effi- ciently add new learning material to your existing knowledge. At the end of each section of the digital course book, you will find self-check questions. These questions are designed to help you check whether you have understood the con- cepts in each section. For all modules with a final exam, you must complete the knowledge tests on the learning platform. You will pass the knowledge test for each unit when you answer at least 80% of the questions correctly. When you have passed the knowledge tests for all the units, the course is considered fin- ished and you will be able to register for the final assessment. Please ensure that you com- plete the evaluation prior to registering for the assessment. Good luck! 8 BASIC READING Freeman, E., Robson, E., Bates, B., & Sierra, K. (2014). Head first design patterns (A brain friendly guide). O’Reilly Media. Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1995). Design patterns: Elements of re- usable object-oriented software. Addison-Wesley. Liang, Y. D. (2018). Introduction to Java programming and data structures. Pearson Educa- tion. Liguiori, L. & Liguori, P. (2008). Java pocket guide: Instant help for Java. O’Reilly Media. Oracle (2017). The Java tutorials. Available online. Samoylov, N. (2019). Learn Java 12 programming: A step-by-step guide to learning essential concepts in Java SE 10, 11, and 12. Packt Publishing. Weisfeld M. (2019). The object-oriented thought process (5th ed.). Addison-Wesley. 9 FURTHER READING UNIT 1 Johnson, R., & Moses, D. R. (2008). Objects-first vs. structures-first approaches to OO pro- gramming education: An empirical study. Academy of Information and Management Sciences Journal, 11(2), 95–102. UNIT 2 Rajagopal, D., & Thilakavalli, K. (2017). A study: UML for OOA and OOD. International Jour- nal of Knowledge Content Development & Technology, 7(2), 5–20. UNIT 3 Xing, C., & Belkhouche, B. (2003). On pseudo object-oriented programming considered harmful. Communications of the ACM, 46(10), 115–117. UNIT 4 Ourosoff, N. (2002). Primitive types in Java considered harmful. Communications of the ACM, 45(8), 105f. UNIT 5 Nasseri, E., & Counsell, S. (2010). Java method calls in the hierarchy–uncovering yet another inheritance foible. CIT Journal of Computing and Information Technology, 18(2), 159–165. UNIT 6 Alkazemi, B. Y., & Grami, G. M. (2012). Utilizing BlueJ to teach polymorphism in an advanced object-oriented programming course. Journal of Information Technology Education: Innovations in Practice, 11, 271–282. UNIT 7 Bruno, R., & Ferreira, P. (2018). A study on garbage collection algorithms for big data envi- ronments. ACM Computing Surveys, 51(1), 1–35. 10 UNIT 8 Rashkovits, R., & Lavy, I. (2012). Students’ understanding of advanced properties of Java exceptions. Journal of Information Technology Education: Innovations in Practice, 11, 327–352. UNIT 9 Sousa, B. L., Bigonha, M. A., & Ferreira, K. A. (2018). When GOF design patterns occur with god class and long method bad smells? – An empirical analysis. INFOCOMP: Journal of Computer Science, 17(1), 11–22. 11 LEARNING OBJECTIVES The course Object-Oriented Programming With Java teaches you the basic skills of object-oriented programming. The associated theoretical concepts are directly shown and practiced using the Java programming language. The goal of this course is to enable you to grasp the basic concepts of object-oriented modeling and programming and to differen- tiate between them. In addition, the basic concepts and elements of the Java program- ming language are explained and you can gain experience in using them. After finishing the course, you will be able to create your own solutions to concretely described prob- lems. 12 UNIT 1 INTRODUCTION TO OBJECT-ORIENTED SYSTEM DEVELOPMENT STUDY GOALS On completion of this unit, you will have learned … – what is meant by the term object orientation. – what objects are and what they consist of. – which phases make up the software development process. – the basic principles of object-oriented software development. 1. INTRODUCTION TO OBJECT-ORIENTED SYSTEM DEVELOPMENT Case Study As a developer, Ms. Koch is supposed to program an online shop for the sale of media of all types (books, music, films, and games). The customer, Mr. Lange, explains to her which products should be sold and what special offers he has planned. It is now time to begin development and Ms. Koch is considering how best to approach this task. 1.1 Object Orientation as a Way of Looking at Complex Systems Object orientation The term object orientation (abbreviated as OO) refers to an approach in software tech- An approach that sup- nology that was developed primarily to support the development, enhancement, and ports the creation, enhancement, and main- maintenance of complex enterprise IT systems. Here object orientation is a view of com- tenance of complex enter- plex systems that conceives these systems as an interaction of abstract or real entities— prise IT systems. Here, the the objects themselves. IT system is described as the interaction of com- plex objects. “Object orientation” therefore is not a programming language or a modeling language. It is not an operating system, program or application, nor is it a process model, develop- ment method or environment or database. But there are languages, methods and databa- ses that support the object-oriented approach in particular ways. The widespread acceptance of object orientation in industrial applications began in the early 1990s. A key factor here was the very high cost of service and advanced development of large IT systems, among other factors. Typically, enterprise applications are being developed on an ongoing basis and adapted to meet business and technical trends. Thus, as the functional scope of IT systems grows, so too does the number of lines of program code (LOC). Often enterprise information systems contain several millions of lines of pro- gram code that have been written jointly by several hundred developers. Object orientation is part of the historical development of programming paradigms and today is the foundation for virtually all development projects for enterprise information systems. The table below provides an overview of the historical development of program- ming concepts, their typical elements, and their areas of application. 14 Table 1: Overview of the Historical Development of Programming Concepts Programming concept Typical elements Areas of application Machine code 1001001; 1 and 0 as only possi- Of historical interest only; no ble expression values longer in use today Assembly code movb $0x61; processor com- Controllers for electrotechnical mands and direct address of devices (fans, motors, air-condi- technical memory addresses tioners), reactive systems (sen- sor systems), embedded pro- gramming Imperative programming WHILE, FOR, GOTO; an advance Small programs to solve simple on assembly code, allow loops tasks, usually in special pro- and targeted jumps gramming languages Structured programming Procedures; structuring a pro- Simple Web applications, tech- gram in procedures (functions) nical control components and subprocedures (subfunc- tions) Object-oriented programming Classes, objects, associations; a Large and complex industrial program consists of cooperating software systems objects Component-based development Components, interfaces; parts of Reuse of previously program- a system are combined in a com- med functions; the individual ponent that performs very spe- components are usually pro- cific tasks grammed with object-oriented programming Model-driven Models, code generators; Reuse of simple customizability program code is generated auto- of cross-cutting functions (e.g., matically from software models login mechanisms), the gener- using code generators ated program code can reflect the concepts of object orienta- tion Source: Brückmann & Dreikauss, 2020. 1.2 The Object as a Basic Concept of Object Orientation The concept object is present in the very name “object orientation” and refers to a part of Object a system. For object-oriented programming, this means that an object is a part of a pro- This is a part of a software system. At the time of gram and also that a program developed with object-oriented programming will consist execution, object-orien- almost exclusively of objects. An object can then contain attributes and methods itself. ted systems take the form You can use attributes (also: properties) to store information (e.g., current values of varia- of objects in the main memory of a computer. bles) in an object. The attributes of an object are hidden from direct access from other Attributes objects and thus protected. This means that the values currently saved in an object cannot Elements of objects that be changed by other objects (principle of data encapsulation). are used for saving con- crete values are called attributes. 15 To read and change the attributes of an object, methods of an object are used. With meth- ods (also: functions, operations), an object offers other objects in the system the ability to access, read, change or update its own attributes and perform calculations. An object Method accesses another object by invoking a method on the object. Elements of objects that are used to create, read, change, and perform cal- Example Scenario culations of the values of attributes are called methods. A clock, as shown in the following figure, should be replicated as a digital object as defined in object-oriented programming. First, a name is created for the clock. In this case the name of the object is “Digital Clock.” Next, the typical attributes of a clock are identi- fied, i.e., information that is needed to describe the object “Digital Clock”: the “current time” and the “current time zone.” Now, the methods of the object are needed, i.e., the functions that the object “Digital Clock” must provide to realize its function in relation to other objects. Here these are “set time,” “output time,” and “set time zone.” Figure 1: Drawing of a Clock Source: Brückmann & Dreikauss, 2020. 1.3 Phases in the Object-Oriented Development Process Before beginning the actual programming of complex IT systems, all developers must understand exactly what specifically the system should do, what information has to be saved in the system, and who is going to use the system later and for what purpose. In addition, the rough structure of the system must be defined by the system architect in the form of a system architecture. Thus, before Ms. Koch can actually begin programming the online shop, she must analyze the problem or task and consider which objects the system should consist of. Only then can she begin actual goal-directed programming. The process of going through these dif- 16 ferent phases is called the software development process (also: SW process). The goal of Software development a SW development process is to develop a functional system that meets the requirements process This process consists of of the clients with respect to functionality, quality, and development costs. activities in which the goal is the development, An object-oriented development process consists of three different phases: enhancement, or servic- ing of software. This proc- ess is divided into several Object-oriented analysis (OOA) phases. Object-oriented design (OOD) Object-oriented programming (OOP) The object-oriented analysis determines what a system should do. The goal of the analysis is to gain a comprehensive understanding of the functional relationships within the sys- tem being built. Here, objects in the real world are replicated in a functional model and only the properties (attributes) that are relevant to the system are included. This analysis model acts first as a means of communication between the developers and the client and/or the users of the system. It is also the starting point for the next phase: the object- oriented design. The object-oriented design forms a bridge between the analysis and implementation. Object-oriented design Here, the design of the system is completed using the analysis model as a basis: The func- This is a phase in the object-oriented SW proc- tional analysis model is extended by adding technical information so that a programmer ess. Its goal is the techni- can implement the program code based on the design. In this step, you define which types cal design of the system, of objects are needed, which attributes and methods they will have and which objects will building on the analysis model. The result is the cooperate with each other and in what manner. For complex systems, this task can only be design of the system. completed by experienced system architects. The quality of the design is generally crucial for the quality of the programmed system and any future work to extend or customize the system. In object-oriented programming a system design is translated into functioning program Object-oriented code. The developer programs the program code following the specifications defined dur- programming This is a phase in the ing the design. The analysis and design are necessary preliminary tasks, but the actual IT object-oriented SW proc- system is developed exclusively from the implemented program code. That is, if the pro- ess. The goal is the devel- grammers fail to adhere to the specifications, there is a risk that design decisions will not opment of functional pro- gram code using the be implemented appropriately and the system will ultimately behave differently than was design as a basis. The intended. Furthermore, errors during analysis and design can be propagated in the pro- result is the finished pro- gram. gram code if the developer fails to recognize them early. Example For Ms. Koch, this means that, in implementing her online shop, she will first have to exhaustively examine Mr. Lange's wishes and expectations. In this way, she is able to arrive at an understanding of what business activities are relevant for an online shop and how exactly the individual processes (e.g., product ordering, payment processing, collections) will operate. Next, she must consider the technical design of the online shop. This does not, however, refer to the visual appearance of the user interface, but to the question of which (techni- cal) objects the online shop should consist of and how these should cooperate. In addi- 17 tion, Ms. Koch must decide which technologies should be utilized: She can either select and adapt an existing shop system or program a new one. Also relevant is the question of which database will be considered and which programming language she would like to use in programming the online shop. 1.4 Basic Principle of Object-Oriented System Development As previously discussed, object orientation is a way of looking at complex systems as an interaction of cooperating objects. Any system can in theory also be planned and built without object orientation. But the experience of the past 20 years of software engineering has shown that with the consistent application of object orientation there are fewer prob- lems in the scaling, stability, and extensibility of IT systems. Object orientation in software development can therefore be understood as a principle and a means of managing the complexity of software systems. Especially the quality goals of simple extensibility, better testability, and better maintaina- bility can be achieved relatively easily with object-oriented concepts. Example Without exploring the theoretical background, the following example scenario of a simple coffee machine shows how object orientation affects the viewing of technical systems. 18 Figure 2: Example Scenario of a Simple Coffee Machine Source: Brückmann & Dreikauss, based on Reviewland, 2017. In the figure above, a schematic cross-sectional view of a coffee machine is shown. Trans- lated into the terms of object orientation, the coffee machine can be considered an “inter- action of cooperating objects,” as shown in the figure below. The water tank object is con- nected to the water pipe object. The water pipe includes a non-return valve object and is connected to the filter object. The heating element object heats the water pipe and the hot plate object. The hot plate keeps the coffee pot object warm. The coffee pot fills up through the filter object. 19 Figure 3: Interaction between Objects in a Coffee Machine Source: Brückmann & Dreikauss, 2020. A little later Mr. Lange decides that he would like to control the coffee machine with a clock, and instead of the water tank would rather have a direct connection to the drinking water network. The figure below now shows an extended coffee machine as understood in the terms of object orientation: The water tank has been replaced with the drinking water supply. Now the water pipe no longer cooperates with the tank, but instead with the drink- ing water supply (shown by the connecting line between drinking water supply and water pipe). A clock object has also been associated with the heating element. Through this con- nection, the function of “heating” the heating element can be controlled with the clock, but all other existing internal relationships within the coffee machine remain unchanged. Figure 4: Advanced Coffee Machine Source: Brückmann & Dreikauss, 2020. 20 This very simple example illustrates a key aspect of object-oriented systems: The division of internal elements into areas that are responsible for a very specific function, and the interaction among individual objects. The figure above shows the responsibilities of the objects of the coffee machine. Even if the coffee machine cannot be programmed entirely —because water, coffee and heat are still needed—IT systems are designed and built according to a similar principle. Table 2: Objects of a Coffee Machine Objects Responsibilities/function Water tank, later replaced by drinking water sup- Water supply ply Water pipe Transport water Non-return valve Control the water flow direction Heating element Convert electrical energy into heat Hot plate Heat coffee pot Filter Hold coffee grains and allow water to flow through Clock Trigger signal when configured time is reached Source: Brückmann & Dreikauss, 2020. With a clear encapsulation of responsibilities into very specific objects and a clear defini- Encapsulation tion of interfaces, objects can later be interchanged (in our example the water tank was The creation of objects specifically with a view to interchanged with the drinking water supply) or extended (in our example the extension of their use in encapsulated the coffee machine happened by adding a clock for time control) without affecting the sta- functions and tasks. bility and functionality of the overall system. This in turn simplifies the process of quality Other objects can invoke these specific functions assurance, since the entire system does not have to be tested again but just the affected and tasks through interfa- parts of the system. ces. SUMMARY Object orientation is an approach to complex systems in which the sys- tem is described as the interaction of cooperating objects. In object-oriented system development, things in the “real” world are replicated with objects in the “digital” world. Only the values and func- tions that are relevant to the purpose of the system are considered. The digitally replicated objects save values in their attributes and can calcu- late values in their methods. Object-oriented programs consist of coop- erating “digital” objects. The cooperation of objects is realized through the mutual calling of methods. 21 The object-oriented development process consists of the phases object- oriented analysis, object-oriented design, and object-oriented imple- mentation. The goal of the development process is to develop a system that meets the requirements of the client with respect to functionality, quality, and cost. By dividing systems into individual objects with very specific responsi- bilities, object orientation supports development, enhancement, and quality assurance on complex industrial software systems. 22 UNIT 2 INTRODUCTION TO OBJECT-ORIENTED MODELING STUDY GOALS On completion of this unit, you will have learned … – how the concepts object and class fit together. – how classes are identified. – how attributes of classes are described. – how methods of classes are described. – how associations between classes are described. – what the Unified Modeling Language (UML) is. 2. INTRODUCTION TO OBJECT-ORIENTED MODELING Case Study Now that Ms. Koch is certain that her project is going to last several weeks, she has deci- ded to use an object-oriented approach in analyzing the online shop for Mr. Lange. To this end, she would like to document all the objects that are needed, identify their attributes and methods, and document them in the appropriate form. Though she has a rough idea of how she can represent the online shop and the products, she also wants to be sure that she understands and has thought everything through before programming. Here, Ms. Koch needs to know how to identify objects and what methods to use, both in represent- ing the elements of objects (i.e., attributes and methods) and the cooperation between objects. 2.1 Structuring Problems With Classes We have learned about the object as a basic concept in object orientation. An object is a self-contained entity that is capable of action, for example the auto “E-CL 2343,” the lamp “Kyist,” the customer “Mr. Meier,” or the contract “P-DFD-23.” In object-oriented develop- ment, objects in the physical (real) world are replicated as objects in a programming lan- guage. For example, the real customer Hans Meier has a digital equivalent in the form of a digital object “Hans Meier.” The actually existing customer (Mr. Hans Meier) is replicated in the form of a “digital object” in the relevant programming language of the IT system. In this digital replication, however, only the most important attributes are included, such as first name and last name, birthdate, or sex. In most cases attributes such as hair color, eye color, or color of clothing will not be relevant as they are not needed to perform the tasks of the system. Class A class in object-oriented programming provides the structure that is needed for the crea- This is a structure that is tion of a digital object. Any desired number of objects can be created with a class as a used to create digital objects which are the cen- basis. All objects created from one class will have the same structure, i.e., the same attrib- tral elements in the utes and methods. A class is thus roughly comparable to a Word document template, and object-oriented SW devel- an object is a Word document that is created from this template. Which classes an object- opment process. oriented system consists of and what the structure of the required classes looks like will be determined in the object-oriented design phase. The starting point for the design are the identified and specified requirements. Object-oriented programming for IT systems consists (almost) exclusively of the implementation of classes. That is, the developer defines the structure of classes, i.e., which elements (attributes and methods) make up the objects that are created from the classes. An object-oriented system then creates the appropriate objects where they are needed, e.g., from database entries or user inputs. The description of the classes guarantees that all objects that are created based on these 24 classes behave identically. All objects of the same class have the same attributes and can use the same functions and routines (the “methods”). All objects created from the same class can thus be processed by the functions of the system in the same way. The main tasks in the analysis, and later in the design, are the identification and descrip- tion of classes. Although the approach is called “object orientation,” it is actually the classes that play a prominent role in the approach. For the analysis and design of the online shop, Ms. Koch therefore must first identify appropriate classes which will later serve as a template for programming the online shop. 2.2 Identifying Classes In the first step, an analysis model of the system is created which will be used, during Analysis model analysis, to define what a system should do and then on that basis to later define, during This is the result of the object-oriented analysis, design, which classes the system should consist of. Possible candidates for classes must which is used for commu- be identified and listed based on the defined problem statement and the requirements. nication between the developers and the client and/or the users of the An established procedure for the identification of classes can be described as follows: system. 1. Mark all nouns in a problem statement as candidates for classes. 2. Check whether the nouns that have been identified can be described using other nouns or if they have associations or dependencies with other nouns. If one of the two statements is true, the noun is modeled as a class. 3. If the noun is used to add details to another noun, it is modeled as an attribute of a class. 4. Check all remaining words that are neither a class nor an attribute for relevance and, if necessary, remove them from the list of candidates for classes. Example The products that Mr. Lange sells in the online shop will be media of all types, in particular books, music products, films, and games. Each product has a manufacturer, a title, and a product number. Books and games have an author, films have a director, and music prod- ucts have a performer. Step 1: After listing all of the nouns, the list will consist of the following entries (the nouns are listed in singular form only): online shop product media type book music product film 25 game manufacturer title product number author director performer Steps 2–4: Check candidate for class, attribute, and relevance in general. Online shop: not relevant because it designates the system as a whole Product: relevant as class Media: not relevant because it only describes a product Type: not relevant because it only describes a product Book: relevant as class because it is refined by attributes Music product: relevant as class because it is refined by attributes Film: relevant as class because it is refined by attributes Game: relevant as class because it is refined by attributes Manufacturer: relevant as attribute because it fits description of classes Title: relevant as attribute because it fits description of classes Product number: relevant as attribute it fits because description of classes Author: relevant as attribute because it fits description of classes Director: relevant as attribute because it fits description of classes Performer: relevant as attribute because it fits description of classes The figure below shows the identified classes of an example scenario. Classes are always shown in the form of a rectangle. The name of the class is written in the rectangle. Figure 5: Identified Classes Source: Brückmann & Dreikauss, 2020. 26 2.3 Attributes as Properties of Classes As described above, classes (and thus also objects) consist of attributes and methods. The attributes (also: property of classes) are static elements of classes. Concrete values of the object can be saved in an attribute. Attributes are used exclusively for saving values and can be understood as free memory inside of an object. In summary, the values of all attrib- utes of an object describe its state. Objects that have been created from the same class and whose attributes have the exact same values, are identical. Example A class “Customer” was identified for the online shop. For each customer, the last name, first name, birthdate, and sex must be saved. Last name, first name, birthdate, and sex are thus modeled as attributes of the class “Customer.” Figure 6: Attributes of the “Customer” Class Source: Brückmann & Dreikauss, 2020. As shown in the figure above, attributes are listed in a separate rectangle below the class name. A class with attributes thus consists of two adjacent rectangles: The top rectangle contains the name of the class and in the bottom rectangle the attributes of a class are listed. When modeling attributes, the properties described in the table below, among others, can be defined. Of these properties, the name, at a minimum, is required in an analysis model. The other properties can also be defined now, but this is not mandatory. The remaining properties will be defined during the course of the SW development process. Table 3: Properties of Attributes Properties of an attribute Description Example Name Name of the attribute firstname 27 Properties of an attribute Description Example Data type Defines how the values of the Date (date) attribute will look like, i.e., String (text) whether they are a number, a Integer (number) string, or a date Constant (yes/no) Specifies whether the value of Rounded Pi: 3.1415 the attribute can change or not Default value Specifies the default value of the 2020-01-01 attribute Source: Brückmann & Dreikauss, 2020. Example After identifying possible classes, now the attributes of the classes must be identified. Good candidates for attributes are nouns that can be used for describing or adding details to other nouns. In the figure below, the attributes identified in the example scenario online shop are added. Figure 7: Identified Attributes of the Classes Source: Brückmann & Dreikauss, 2020. 2.4 Methods as Functions of Classes Methods Methods (also: functions, operations) are dynamic elements of classes. They contain algo- These are dynamic ele- rithms, statements, and processing specifications that can be used to create, calculate, ments of classes and describe the behavior of modify, and delete values. The results of the methods can be saved in attributes of the classes such as defining class or in newly created objects. Methods are used to describe the behavior of objects, specifications for the cal- i.e., what an object does. Methods can thus be used to program calculations of values and culation, modification, and creation of attributes the application of business rules or specifications in the creation and deletion of objects. and objects. 28 When modeling methods, the elements described in the table below can be defined. The name, at a minimum, is required in an analysis model. Detailed information on the return value, parameters, and the function of the method can also be added one by one over the course of the development process. Table 4: Properties of Methods Elements of methods Description Example Name Name of the method getLastname() Parameter Required objects and values that (Date birthdate), (String are needed for processing the lastname, String firstname) method (Integer number1, Integer number2) Return value Defines the data type of the Date object in which the result of the String method is stored Integer Source: Brückmann & Dreikauss, 2020. Example We now need to define the methods for the class “Customer” that was provided with attributes above. What is important here is that in each case the values stored in the attributes can be read again. As described above, it is only possible to access attributes from outside via methods, and never directly. Therefore the class “Customer” has to sup- ply for each of its attributes a method that returns the current value of the attribute. Figure 8: Attributes and Methods of the “Customer” Class Source: Brückmann & Dreikauss, 2020. 29 As shown in the figure above, the methods of a class are modeled in an additional rectan- gle below the attributes. A class with methods thus consists of three adjacent rectangles: The top rectangle contains the name of the class, the middle rectangle contains the list of attributes of a class, and the bottom rectangle contains the list of the methods of a class. 2.5 Associations between Classes All of the elements of an object-oriented system are programmed in the form of classes. Interaction between different classes is only possible when, during the development proc- Associations ess, associations have been defined between classes. In addition, cooperation between These describe depend- objects is only possible when associations have been defined between classes. encies and relationships between classes, thereby enabling cooperation Typical associations between classes are shown in the following table. between objects. Table 5: Typical Associations between Classes Association types Description Example “has/knows” This type of relationship expresses the A policyholder has children. fact that one class “has” or A contract has insurance conditions. “knows” another class. A calendar has months. A seller knows their customers. “consists of” This relationship expresses the rela- A car consists of an engine, 4 wheels, 3 tionship in which a class is part of doors, 1 transmission, and 2 seats. another class. It is used when a class is A house consists of a roof, 23 windows, a larger construct with elements that 2 doors, cannot be described using simple 6 rooms, and 1 stairwell. attributes. “is a” This type of relationship expresses the A passenger car is an automobile. fact that a class A is a class B by type, A truck is an automobile. but it has a more specific meaning and A customer is a person. may have different attributes and A book is a product. methods than class B. A hedgehog is a mammal. Source: Brückmann & Dreikauss, 2020. Lines and arrows are drawn between the relevant classes so that relationships can be graphically represented in addition to classes, attributes, and methods. The simplest way to create relationships is with a continuous line connecting the two classes. Additional information can be added to the relationship, in addition to the continuous line, as shown in the table below. 30 Figure 9: Representing Relationships Source: Brückmann & Dreikauss, 2020. Quantity specifications for relationships can also be defined using multiplicities (also: Multiplicities cardinalities). This information is shown at the end and at the beginning of a relationship: These are quantity speci- fications for associations The information to the left of “...” represents the lower bound of the quantity specifica- between classes. With tions and the information on the right of “...” is the upper bound. The table below includes multiplicities, you can an overview of possible quantity specifications. specify how many objects of a class can be associ- ated with how many objects of another class. 31 Figure 10: Multiplicities in Relationships Source: Brückmann & Dreikauss, 2020. Example To identify and add possible associations to the “online shop” example scenario, we must return to the original text: “The products that are sold by Mr. Lange in the online shop should be media of all types, i.e., books, music products, films, and games. Each product has a manufacturer, a title, and a product number. Books and games have an author, films have a director, and music products have a performer.” These are represented graphically in the figure below. Other than the “is a” associations of the class “Product” with the classes “Book,” “Music product,” “Game,” and “Film,” no other associations are currently needed. 32 Figure 11: Example Scenario with Additional Associations Source: Brückmann & Dreikauss, 2020. 2.6 Unified Modeling Language (UML) The application of the concepts (class, object, method, attribute) goes through all phases of an object-oriented development process. To appropriately document the results of the phases OOA and OOD, the identified classes and their associations are documented in a standardized modeling language. The Unified Modeling Language (or UML) is a graphical modeling language that was Unified Modeling developed in the early 1990s with object orientation. UML now includes 13 different dia- Language This is a universal model- gram types for modeling different aspects of a system. An overview of the UML diagrams is ing language that is a de shown in the figure below. Generally, a distinction is made between diagrams for model- facto global standard for ing structure and modeling behavior. Structure diagrams are used for diagramming modeling in IT systems. Structure diagrams structure, elements, and composition, as well as the interfaces of systems. In simple These are UML structure terms, structure diagrams are used to model what a system consists of. Behavior dia- diagrams used for model- grams, on the other hand, are used to model what happens in a system. ing structure, elements, composition, and interfa- ces of systems (e.g., class diagram). 33 Figure 12: Overview of UML Diagram Types Source: Brückmann & Dreikauss, 2020. Classes with their attributes, methods, and associations are modeled with the UML class Class diagram diagram. The UML class diagram is one of the most commonly used documentation forms This is a structure dia- in object-oriented system development. All other structure diagrams of the UML are based gram of UML which is used for modeling more or less on the modeling concepts of the class diagram. classes, including their attributes, methods, and Object diagrams are a special form of class diagrams. They can be used to model specific associations. Object diagram instances of classes. Here, objects whose attributes contain values are modeled. The fig- A structure diagram of ure below contrasts the class “Customer” with two concrete objects of the class “Cus- UML which is used for tomer.” Objects differ from classes in that each object is identifiable with a unique ID (here modeling concrete objects, including con- “id1” and “id2”), shown to the left of class name followed by a colon “:” and a concrete crete attribute values as value is shown for each attribute of an object. instances of classes. All objects of a class have the same attributes, only their values can differ. 34 Figure 13: Objects and Classes Source: Brückmann & Dreikauss, 2020. With the modeling concepts class, object, attribute, method, and association, we have thus far discussed the basic notation elements. All other notations, such as inheritance or interfaces, are based on these basic elements, which will be introduced later when they are needed for object-oriented programming. SUMMARY Before programming, both the problem and the design of the object-ori- ented system are modeled in the phases object-oriented analysis (OOA) and object-oriented design (OOD). Here, classes are modeled with their attributes and methods as well as associations between classes with UML class diagrams. Possible candidates for classes are identified through an analysis of the problem based on the relevant nouns. Next, these classes are extended by adding attributes and methods as required by the problem. After the identification of attributes, these can be characterized more precisely with a name, a data type, the information as to whether it is a constant, and if applicable a default value. Methods, on the other hand, are described by their name, required parameters, and their return value. 35 Associations between classes can vary in type; in addition to the “has/ knows” relationship, there are also the “consists of” and “is a” relation- ships. Individual associations can be refined by labeling with roles, arrows, and cardinalities. UML provides appropriate graphical modeling concepts for standardized representation of analysis models and the design of object oriented sys- tems. The UML class diagram and UML object diagram are particularly well suited for modeling structures. In addition, UML includes various behavior diagrams for modeling the process flows of a system. 36 UNIT 3 PROGRAMMING CLASSES IN JAVA STUDY GOALS On completion of this unit, you will have learned … – what elements are required to run and program Java applications. – which basic elements a Java class consists of and how to program them in Java. – how attributes of classes are programmed in Java. – how methods of classes are programmed in Java. – how to specify what a Java program should execute when it starts. 3. PROGRAMMING CLASSES IN JAVA Case Study Once Ms. Koch has developed an object-oriented model for the makeup and structure of the online shop, she would like to take the first steps towards object-oriented program- ming. Now that she understands that object-oriented systems consist of a set of cooperat- ing objects, she wants to know how to create classes and objects with the Java program- ming language and what preliminary steps she needs to take. 3.1 Introduction to the Java Programming Language Programming In simple terms, programming (also: implementation) consists of three different activi- This activity has the goal ties: of developing program code that can be execu- ted as a program or pro- 1. Programming, i.e., production of program code (also: source code, source text, pro- gram component after gram text) compilation on a com- puter. 2. Compiling, i.e., automatic translation of the program code produced into a form that can be executed by a computer 3. Executing a program, i.e., starting and running the generated and compiled program code to see whether the system performs as expected While the program code can be written with a simple text editor, software will be needed by no later than the time of translating (also: compiling) the program text written by the developer into executable machine code. This translation software is called a compiler. Compiler Compilers are available for every programming language. When the program text has This is software that been compiled by the compiler, it can be started and executed in a runtime environment. translates program code into a form that can be For many programming languages, the operating system of a PC (e.g., Windows, Linux, executed by a computer. MacOS) provides the runtime environment. Because operating systems have different functions and properties, programs have to be reprogrammed/recompiled for each oper- ating system. In the example shown below are all the required elements for development with the C programming language. 38 Figure 14: Development with the C Programming Language Source: Brückmann & Dreikauss, 2020. The Java programming language is a platform-independent programming language. A program written in Java does not have to be changed for each operating system. Java dif- fers from other programming languages in that a Java runtime environment (JRE) must be installed on devices before you can run a Java program. The Java compiler translates the programmed source text into what is called “bytecode.” This bytecode is then loaded, Bytecode started, and executed by the Java runtime environment. Because a Java runtime environ- This is the form a Java program takes after it has ment is available for virtually every operating system, a Java program can run on a Linux, been compiled, which can Windows, or Mac computer. The figure below provides an overview of required elements be executed as a program in development with Java. In contrast to the figure above, here an additional runtime from a Java runtime envi- ronment (JRE). environment is required to allow execution on different platforms. 39 Figure 15: Development with the Java Programming Language Source: Brückmann & Dreikauss, 2020. The Java runtime environment (JRE) is required to run a Java program as a user. The Java Java virtual machine runtime environment consists of the Java virtual machine (JVM) and the Java class (JVM) library. The JVM is the software that interprets the bytecode and both starts it and runs it This is an operating sys- tem-specific software that on the operating system being used. The Java class library provides functions that are can run Java programs in already part of the Java programming language so that commonly used data structures bytecode form on a com- (e.g., lists or strings) can be reused by the programmer, but without having to be reimple- puter. mented each time. To develop software in the Java programming language as a software developer, a Java Java software devel- software development kit (Java SDK) is required. The Java SDK consists of a Java com- opment kit (Java SDK) piler, a Java virtual machine, the Java class library, and other tools. This is a basic tool for a Java developer. It includes a compiler, which generates bytecode and a JVM for running Java programs. TIP To facilitate the development process, applications called integrated develop- ment environments (IDE) are used. For Java, there are for example, Eclipse, Net- Beans, IntelliJ, or BlueJ as free IDEs—but there several others available. Your tutor will provide recommendations with download links and instructions so that you can follow examples and find practical exercises. 40 3.2 Basic Elements of a Class in Java A class in the programming language Java has a unique name and can contain attributes and methods. The program code of a class is saved in Java in a text file with the file ending *.java. A separate file is created for each class. For each class (and for each Java file), the Java compiler creates a class with the ending *.class in which the compiled bytecode of a class is saved. In the figure below the basic structure of the Java class “Customer” is shown again, although here without attributes. To create a class, the following four elements at a mini- mum are required: the visibility modifier, the class keyword, the name of the class, and a few curly braces. Figure 16: Structure of the “Customer” Class Source: Brückmann & Dreikauss, 2020. The class “Customer” can be used as shown in the figure above—the Java compiler would not return an error during translation into bytecode. In the table below the elements of the basic structure are described in greater detail: Table 6: Basic Elements of a Class in Java Element of a class Description Example Visibility modifier Defines the visibility of the class for other public classes Keyword for the class declara- Indicates to the Java compiler that a Java class tion class is programmed in the following Class name Defines the name for the class and is used Customer as a file name. The class “Customer” is pro- grammed in a text file “Customer.java” 41 Element of a class Description Example Curly brackets Marks the contents of a class (attributes { … } and methods); everything inside the braces belongs to a class Source: Brückmann & Dreikauss, 2020. The following rules apply for the name of the class: Begins with an upper case letter Consists of Unicode characters (with restrictions, e.g., no empty characters, no umlauts) Can theoretically be of any length (only limited by the maximum length of a file name) Cannot be a keyword (e.g., class or public) If the class name contains multiple words, these are combined without separator (e.g., WordWord, NameOfClass) 3.3 Attributes in Java After programming the first basic structure of the class “Customer,” the required attributes should now be added. The figure below shows the class “Customer” with the attributes added. An attribute in Java is described with the following elements at a minimum: the visibility modifier, the data type, and the attribute name. The string data type shown below is used for strings. 42 Figure 17: “Customer” Class with Attributes Added Source: Brückmann & Dreikauss, 2020. In addition, values can already be assigned for attributes during programming (also: default values). In the following example, two attributes are shown for which a default Default value value is assigned to each in the source code: A value that is assigned to an attribute automati- cally when the object is private boolean isPremiumCustomer = false; created is a default value. private int quantityOfPurchases= 0; The elements of the basic structure are described in greater detail in the table below: Table 7: Basic Elements of an Attribute in Java Element of an attribute Description Example Visibility modifier Defines the visibility of the private attribute for other classes Data type of the attribute Defines the data type of the String customer attribute and thereby deter- mines the number and type of values that can be stored in the attribute. A data type is either a primitive data type or a class, which is called a reference data type (e.g., String or Customer). 43 Element of an attribute Description Example Attribute name Defines the name for the attrib- lastname, firstname, sex ute of the class; each name can only be assigned once inside a class. Default value Defines the initial value of the =0 attribute; this value is assigned =1 to the attribute when creating = false an object of the class. Semicolon Marks the end of the attribute ; declaration. Source: Brückmann & Dreikauss, 2020. The following rules apply for the name of an attribute of a class: Begins with a lower case letter Consists of Unicode characters (with restrictions, e.g., no empty characters, no umlauts) Can theoretically be of any length Cannot be a keyword (e.g., public or class) Is case sensitive (i.e., name is a different attribute than nAme) If the attribute name contains multiple words, these are combined without separator (e.g., attributeAttribute, nameOfCustomer) 3.4 Methods in Java With the knowledge acquired thus far we can now program simple classes with attributes. We can now already store data in objects in the form of attribute values. Next, methods will be implemented which, as dynamic elements of classes, can create, calculate, modify, and delete the values of attributes. As previously noted, access to the attributes of an object by other objects is only possible through methods, but never through a direct access to the attributes of another class Principle of data encap- (encapsulation principle). Therefore, methods are also needed to read the values of sulation attributes and make them available to other classes. Here, an object can never directly access attributes of another object. Read- In the figure below, a fully implemented class “Customer” is shown in which the elements ing or changing attributes of a method are explained using the method getLastname(). should only be possible through methods. 44 Figure 18: Methods of the “Customer” Class Source: Brückmann & Dreikauss, 2020. The table below contains the minimal elements that are required in Java for the imple- mentation of a method. Table 8: Basic Elements of a Method in Java Element of a method Description Example Visibility modifier Defines the visibility of the public method for other classes 45 Element of a method Description Example Return data type of the method Defines the data type of the String customer void object in which the result of the method is output after process- ing the method body. Here, a primitive data type or a class (e.g., string or customer) is declared. When the method does not output a result, the return data type is set to void. Method name Defines the name for the getLastname() getFirstname() method; a method name can only be used more than once in a class if the number or data type of the parameters are different Parameter list List of required objects and their (Date birthdate), (String last- data types which are needed for name, String firstname) processing the method; if no (Integer number1, Integer num- parameters are defined, the list ber2) remains empty () Method body Contains the specific statements result = number1 + number2; for what is done when the return lastname; method is invoked and in what order. Each statement ends with a semicolon “;”, therefore the “;” in method bodies is often the last character of a program line. The statements in a method body are processed in sequence from the top down. If a return data type is defined for the method, the last state- ment of the method body begins with the keyword return. Source: Brückmann & Dreikauss, 2020. The following rules apply for the name of the method: Begins with a lower case letter Consists of Unicode characters (with restrictions, e.g., no empty characters, no umlauts) Can theoretically be of any length Cannot be a keyword (e.g., public or class) Is case sensitive (i.e., method() is a different method than mEthod) Signature An additional concept for methods in Java is the signature. Methods can be uniquely A signature uniquely identified using their signature. The signature of a method consists of the name of the identifies a method and consists of the name of method and the parameter list. The return data type is not a part of the signature. Each the method and the signature can only occur once in a class since only then can the JRE determine which parameter list. method should be invoked and processed at the runtime of the program. In other words, the name of a method can be assigned more than once in a class as long as the parameter list is different. 46 CODE EXAMPLE 1 Here, the names and the signatures are different: public void login () {…} public void logoff () {…} CODE EXAMPLE 2 Here, both the parameter lists and the signatures are different: public int addtoShoppingCart (Product product) {…} public int addtoShoppingCart (Product product, int quantity) {…} CODE EXAMPLE 3 Here, only the return data types are different, but not the method names or the parameter lists. The signatures are identical: public boolean pay (boolean test) {…} public void pay (boolean test) {…} To access the attributes of a class, any number of method names can be assigned. How- ever, in general, names should be chosen so that it is easy to recognize what the method actually does. Getter and setter methods are used for writing and reading attributes. A Getter and setter getter method returns the value of an attribute. A setter method changes the value of an methods These are special meth- attribute to the value that is passed as a parameter to the setter method. ods used for reading, changing attributes, and implementing the princi- Example ple of data encapsulation. A class “Customer” fully modeled with getter and setter methods is shown in the figure below. It makes it possible both to access the saved values of the attributes (via the getter methods) and to change the values (via the setter methods). 47 Figure 19: Getter and Setter Methods for the “Customer” Class Source: Brückmann & Dreikauss, 2020. A relevant implementation is also shown in the figure below using the example of the attribute. For all other attributes, the implementation of the getter and setter methods is similar; only the names of the methods and parameters are different. The basic structure, however, remains the same. Nonetheless, please note here that in the following figure the parameter of the setter method setLastname was named with lastname just as with the class private attribute lastname—which does not strictly have to be done this way. But to differentiate between these two in such a case, the keyword this is used here, which can be used to refer to the object itself and thus to the class attribute (this.lastname). 48 Figure 20: Implementation of Getter and Setter Methods for the Attribute of the “Customer” Class Source: Brückmann & Dreikauss, 2020. To execute the statements implemented in a method body, the relevant method must be invoked. Methods can be invoked from within other method bodies of the same class or from method bodies of another class. A method is invoked using the name. CODE EXAMPLE 1 Invocation of the method getLastname() inside the class “Customer” String id1= getLastname(); Here, the getter method of the attribute lastname is invoked to store the value of lastname in a local variable id1. CODE EXAMPLE 2 Invocation of the method setLastname() inside the class “Customer” setLastname(“Lange”); Here, the setter method of the attribute lastname is invoked to change the cur- rent value of lastname to the value “Lange”. 49 CODE EXAMPLE 3 Invocation of the method getLastname() of the class “Customer” from another class String id2= customer1.getLastname(); The object that invokes the method getLastname() in Customer has stored an object of the class “Customer” under the variable customer1. By invoking cus- tomer1.getLastname() it is possible to invoke the specific method getLastname() in the object customer1. The value of customer1.getLastname() is stored in the invoking class in the variable id2. CODE EXAMPLE 4 Invocation of the method getLastname() from another class customer1.setLastname(“Lange”); The object that invokes the method setLastname() in customer has stored an object of the class “Customer” under the variable name customer1. By invoking customer1.setLastname(“Lange”) it is possible to invoke the specific method setLastname(String name) in the object customer1. With this method invoca- tion, the “Lange” from another object can be stored as an attribute in the object customer1. Method overloading Method overloading means that there are methods in a class with the same name. With This process is used to overloading, i.e., multiple instances of a method with the same name, you have the ability implement multiple methods with the same as developer to define various method behaviors based on the given parameters. name but different parameter lists inside a class. Example The following method in Mr. Lange's online shop should be used to place a product in the shopping cart. The method provided for this purpose—addToShoppingCart—contains an appropriate product as a parameter. The product is an object from the class “Product.” public void addToShoppingCart (Product product) {…} But in addition to this method, it should also be possible to place more than one of the same product in the shopping cart. For this purpose, the method addToShoppingCart is overloaded by implementing a second method addToShoppingCart which also expects the quantity of the products being added as a parameter, in addition to the product. 50 public void addToShoppingCart (Product product, int quantity) {…} 3.5 Main Method: Starting Point of a Java Program As described above, a consistent implementation of object orientation requires breaking problems down into different classes of a UML class diagram. A Java program likewise consists of a combination of different classes that cooperate together through the invoca- tion of methods. In a Java program, objects are generated from classes at runtime, which in turn can generate additional objects. Therefore, a currently running Java program can be conceived as a network of interrelated objects. For each Java program, however, there is a fixed starting point, i.e., a very specific method is always invoked first when the program starts: the main method. The generation of all the objects that are required by the program starts inside this method. The main method is declared as shown in the figure below. Figure 21: Main Method as the Starting Point of a Class Source: Brückmann & Dreikauss, 2020. The following elements of the main method should be used without changes: visibility modifier (public), declaration of the main method as static method (static), specification that there is no return type (void), name of method (main), and parameter list (String args[]). 51 Only the method body is modified as necessary. The developer can freely decide which class of the program the main method is implemented in. To prevent confusion, however, there should only be one class with a main method. Example A small first prototype of the online shop is shown in the figure below as a class diagram. A class “OnlineShop” has no attributes, but it does have a main method. The class “Cus- tomer” has four attributes and the particular getter and setter methods. Figure 22: Main Method in a Class Diagram Source: Brückmann & Dreikauss, 2020. An appropriate example implementation of the class “OnlineShop” with the main method is shown in the figure below. When executing the program “OnlineShop,” two objects of the type “customer” are created in the method body of the same method. They are then assigned to the variables customer1 and customer2 and the values for the attributes last- name and firstname respectively are saved in the two objects. Then, the value of the attribute lastname for the object customer1 is output in the console. Next, the attribute lastname of customer1 is set to a new value and the current value of lastname is output in the console both for customer1 and customer2. 52 Figure 23: Example on How to Implement a Main Method Source: Brückmann & Dreikauss, 2020. 53 As shown in the example, the program “Online Shop” starts with the main method of the class “OnlineShop.” Starting in the main method, two concrete customers are now cre- ated, i.e., objects of the type customer are created and stored as a variable customer1 and customer2 for subsequent use in the main method of OnlineShop. SUMMARY The Java programming language is a platform-independent program- ming language. By using OS-specific Java runtime environments, a Java program can be run on virtually any operating system without customi- zation. As in object-oriented modeling, Java classes consist of attributes and methods, along with their unique name. Unlike modeling, however, in Java programming there are special conventions and rules that must be followed. For attributes, a visibility modifier—name that is unique throughout the class—and a valid data type must be defined. The following rules apply when programming methods: The signature of a method (name and parameter list) must be unique throughout the class. Each method must also have a declared return data type (or: void), a visibility modifier, and an implemented method body. The pro- gramming in the method body defines what the method does, or more exactly it defines the statements and processing specifications. Access to attributes through another object is usually realized with get- ter and setter methods. This allows for consistent adherence to the prin- ciple of data encapsulation. Methods can be overloaded, i.e., multiple methods that have the same name and differ only in the parameter list can be used. A Java program is always started from the main method. This method is the starting point for all of the activities and sequences in the program. When a class contains a main method that is declared in accordance with conventions, this automatically determines where the program will begin processing statements. 54 UNIT 4 JAVA LANGUAGE CONSTRUCTS STUDY GOALS On completion of this unit, you will have learned … – what primitive data types Java has and what value range they cover. – how variables can be temporarily stored with values. – what important operators exist in Java and how they are used. – what control structures are available and how statements can be repeated for control purposes. – how the visibility of classes and their elements can be defined in targeted ways using packages. 4. JAVA LANGUAGE CONSTRUCTS Case Study Ms. Koch is now ready to implement the elements of a UML class model in Java program code. This means that she can program classes with their attributes in Java and she also knows how to declare methods. Though she is generally familiar with the main method, she is not yet familiar with the elements of the Java programming language that she can use to implement algorithms and business rules inside of a method body. 4.1 Primitive Data Types Information in object-oriented programming is generally stored in attributes of objects. The data type of an attribute determines what information can be stored in an attribute. If the name of a class is defined as the data type of an attribute, then only objects of this class can be assigned as concrete values to this attribute. Primitive data types But with primitive data types there are a number of very simple data types in Java that These are data types are not described by their own class. whose values are not objects, e.g., simple num- bers or logical values. Primitive data types are used to store logical values (true, false), integers (1, 12, 13131), floating point numbers (1.123, 21234.1232) and single characters (t, w, f, d). Primitive data types are simple standard data types that also exist in other programming languages. An overview of primitive data types in Java is shown in the table below. Table 9: Primitive Data Types in Java Type of saved Keyword in values Java Description Examples Logical values boolean Can either be true or false. true Other values are not allowed. false Integer byte 8-bit value range from 123, 0, 23, 120 –128 to 127 short 16-bit value range from –23000, 0, 13231 –32,768 to 32,767 int 32-bit value range from –12332123, 234, –2,147,483,648 to 2,147,483,647 1102379239 long 64-bit value range from 8347829790645, –9,223,372,036,854,775,808 to 13, 0, 34879, 9,223,372,036,854,775,808 789234789274 56 Type of saved Keyword in values Java Description Examples Floating point float 32-bit value range from 1.87236f (simple number number 1.40239846*10–45 to with decimal point and 3.40282347*1038 appended “f”); –3.938e12f ( –3.938*1012 with appen- ded “f”) double 64-bit value range from 1.87236d (Simple number 4.94065645841246544*10–324 with decimal point and to 1.79769131486231570*10308 appended “d”); –3.938e120d ( – 3.938*10120 with appended “d”) Character char A single Unicode character. In ’A’ (= letter A), addition to numerals, letters, and ’2’ (= numeral 2), symbols, also includes control ’\n’ (= control character characters such as blanks, tabula- line break) tor, and line break. Source: Brückmann & Dreikauss, 2020. For integers, the data type int is usually used; smaller data types like byte or short are only used for programming microcontrollers. Another frequently used data type is String, which is used for storing strings. String is not String a primitive data type, but rather a Java class. However, like a primitive data type, String This is a data type that is

Use Quizgecko on...
Browser
Browser