Download as pdf or txt
Download as pdf or txt
You are on page 1of 164

COURSE BOOK

Object-Oriented Programming With Java


DLBCSOOPJ01
Course Book
Object-Oriented Programming With Java
DLBCSOOPJ01
2 Masthead

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

media@iu.org
www.iu.de

DLBCSOOPJ01
Version No.: 001-2022-0922

© 2022 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 distributed in any kind of
form without written permission by the IU Internationale Hochschule GmbH.
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.
Module Director 3

Module Director
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 specializa-
tions include software development, project organization and man-
agement, 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 engineer-


ing from the Technical University Munich (Germany), where he
focused on software engineering, software development, mobile
technologies, usability engineering, and gamification and serious
games.

Mr. Ismailović has founded several innovative start-ups. In previous


leading positions at several 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.
4 Contents

Table of Contents
Object-Oriented Programming With Java

Module Director . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Introduction
Object-Oriented Programming With Java 7
Signposts Throughout the Course Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Unit 1
Introduction to Object-Oriented System Development 12
1.1 Object Orientation as a Way of Looking at Complex Systems . . . . . . . . . 12

1.2 The Object as a Basic Concept of Object Orientation . . . . . . . . . . . . . . . . 14

1.3 Phases in the Object-Oriented Development Process . . . . . . . . . . . . . . . . 14

1.4 Basic Principle of Object-Oriented System Development . . . . . . . . . . . . . 16

Unit 2
Introduction to Object-Oriented Modeling 22
2.1 Structuring Problems With Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

2.2 Identifying Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.3 Attributes as Properties of Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2.4 Methods as Functions of Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

2.5 Associations between Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

2.6 Unified Modeling Language (UML) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32


Contents 5

Unit 3
Programming Classes in Java 38
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

3.5 Main Method: Starting Point of a Java Program . . . . . . . . . . . . . . . . . . . . . . 53

Unit 4
Java Language Constructs 58
4.1 Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

4.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

4.3 Operators and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

4.4 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

4.5 Packages and Visibility Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Unit 5
Inheritance 82
5.1 Modeling and Inheritance in the Class Diagram . . . . . . . . . . . . . . . . . . . . . 83

5.2 Programming Inheritance in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

Unit 6
Important Object-Oriented Concepts 98
6.1 Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

6.2 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

6.3 Static Attributes and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105


6 Contents

Unit 7
Constructors for Generating Objects 110
7.1 The Standard Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

7.2 Overloading Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

7.3 Constructors and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Unit 8
Handling Exceptions with Exceptions 122
8.1 Typical Scenarios of Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 122

8.2 Standard Exceptions in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

8.3 Defining Your Own Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

Unit 9
Programming Interfaces with Interfaces 136
9.1 Typical Scenarios of Programming Interfaces . . . . . . . . . . . . . . . . . . . . . . 136

9.2 Interfaces as Programming Interfaces in Java . . . . . . . . . . . . . . . . . . . . . . 139

Appendix 1
List of References 148

Appendix 2
List of Tables and Figures 150
Introduction
Object-Oriented Programming With Java
8 Introduction

Signposts Throughout the Course Book

Welcome

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 sections.
Each section contains only one new key concept to allow you to quickly and efficiently 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 concepts
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!
Introduction 9

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 differentiate between
them. In addition, the basic concepts and elements of the Java programming 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 problems.
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.

DL-E-DLBCSOOPJ01-U01
12 Unit 1

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
An approach that technology that was developed primarily to support the development, enhancement,
supports the crea- and maintenance of complex enterprise IT systems. Here object orientation is a view of
tion, enhancement, complex systems that conceives these systems as an interaction of abstract or real
and maintenance of entities—the objects themselves.
complex enterprise
IT systems. Here, the “Object orientation” therefore is not a programming language or a modeling language.
IT system is descri- It is not an operating system, program or application, nor is it a process model, devel-
bed as the interac- opment method or environment or database. But there are languages, methods and
tion of complex databases that support the object-oriented approach in particular ways.
objects.
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 develop-
ment 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 mil-
lions of lines of program code that have been written jointly by several hundred devel-
opers.

Object orientation is part of the historical development of programming paradigms and


today is the foundation for virtually all development projects for enterprise informa-
tion systems. The table below provides an overview of the historical development of
programming concepts, their typical elements, and their areas of application.

Overview of the Historical Development of Programming Concepts

Programming concept Typical elements Areas of application

Machine code 1001001; 1 and 0 as only Of historical interest


possible expression val- only; no longer in use
ues today
Unit 1 13

Introduction to Object-Oriented System Development

Programming concept Typical elements Areas of application

Assembly code movb $0x61; processor Controllers for electro-


commands and direct technical devices (fans,
address of technical motors, air-conditioners),
memory addresses reactive systems (sensor
systems), embedded
programming

Imperative programming WHILE, FOR, GOTO; an Small programs to solve


advance on assembly simple tasks, usually in
code, allow loops and special programming
targeted jumps languages

Structured programming Procedures; structuring a Simple Web applications,


program in procedures technical control compo-
(functions) and subpro- nents
cedures (subfunctions)

Object-oriented pro- Classes, objects, associa- Large and complex


gramming tions; a program consists industrial software sys-
of cooperating objects tems

Component-based devel- Components, interfaces; Reuse of previously pro-


opment parts of a system are grammed functions; the
combined in a compo- individual components
nent that performs very are usually programmed
specific tasks with object-oriented pro-
gramming

Model-driven Models, code generators; Reuse of simple custom-


program code is gener- izability of cross-cutting
ated automatically from functions (e.g., login
software models using mechanisms), the gener-
code generators ated program code can
reflect the concepts of
object orientation
14 Unit 1

1.2 The Object as a Basic Concept of Object Orientation


Object The concept object is present in the very name “object orientation” and refers to a part
This is a part of a of a system. For object-oriented programming, this means that an object is a part of a
software system. At program and also that a program developed with object-oriented programming will
the time of execu- consist almost exclusively of objects. An object can then contain attributes and meth-
tion, object-oriented ods itself. You can use attributes (also: properties) to store information (e.g., current
systems take the values of variables) in an object. The attributes of an object are hidden from direct
form of objects in access from other objects and thus protected. This means that the values currently
the main memory of saved in an object cannot be changed by other objects (principle of data encapsula-
a computer. tion).

Attributes To read and change the attributes of an object, methods of an object are used. With
Elements of objects methods (also: functions, operations), an object offers other objects in the system the
that are used for ability to access, read, change or update its own attributes and perform calculations.
saving concrete val- An object accesses another object by invoking a method on the object.
ues are called attrib-
utes.
Example Scenario
Method
Elements of objects A clock, as shown in the following figure, should be replicated as a digital object as
that are used to cre- defined in object-oriented programming. First, a name is created for the clock. In this
ate, read, change, case the name of the object is “Digital Clock.” Next, the typical attributes of a clock are
and perform calcula- identified, i.e., information that is needed to describe the object “Digital Clock”: the
tions of the values of “current time” and the “current time zone.” Now, the methods of the object are needed,
attributes are called i.e., the functions that the object “Digital Clock” must provide to realize its function in
methods. relation to other objects. Here these are “set time,” “output time,” and “set time zone.”

1.3 Phases in the Object-Oriented Development Process


Before beginning the actual programming of complex IT systems, all developers must
understand exactly
Unit 1 15

Introduction to Object-Oriented System Development

• 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 ana-
lyze 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 different phases is called the software development process (also: SW process). Software develop-
The goal of a SW development process is to develop a functional system that meets the ment process
requirements of the clients with respect to functionality, quality, and development This process consists
costs. of activities in which
the goal is the devel-
An object-oriented development process consists of three different phases: opment, enhance-
ment, or servicing of
• Object-oriented analysis (OOA) software. This proc-
• Object-oriented design (OOD) ess is divided into
• Object-oriented programming (OOP) several phases.

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 system being built. Here, objects in the real world are replicated in a func-
tional 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
Here, the design of the system is completed using the analysis model as a basis: The design
functional analysis model is extended by adding technical information so that a pro- This is a phase in
grammer can implement the program code based on the design. In this step, you the object-oriented
define which types of objects are needed, which attributes and methods they will have SW process. Its goal
and which objects will cooperate with each other and in what manner. For complex sys- is the technical
tems, this task can only be completed by experienced system architects. The quality of design of the system,
the design is generally crucial for the quality of the programmed system and any future building on the anal-
work to extend or customize the system. ysis model. The
result is the design
In object-oriented programming a system design is translated into functioning pro- of the system.
gram code. The developer programs the program code following the specifications
defined during the design. The analysis and design are necessary preliminary tasks, but
the actual IT system is developed exclusively from the implemented program code.
That is, if the programmers fail to adhere to the specifications, there is a risk that
design decisions will not be implemented appropriately and the system will ultimately
behave differently than was intended. Furthermore, errors during analysis and design
can be propagated in the program code if the developer fails to recognize them early.
16 Unit 1

Object-oriented pro-
gramming Example
This is a phase in
the object-oriented For Ms. Koch, this means that, in implementing her online shop, she will first have to
SW process. The goal exhaustively examine Mr. Lange's wishes and expectations. In this way, she is able to
is the development arrive at an understanding of what business activities are relevant for an online shop
of functional pro- and how exactly the individual processes (e.g., product ordering, payment processing,
gram code using the collections) will operate.
design as a basis.
The result is the fin- Next, she must consider the technical design of the online shop. This does not, how-
ished program. ever, refer to the visual appearance of the user interface, but to the question of which
(technical) objects the online shop should consist of and how these should cooperate.
In addition, 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 problems in the scaling, stability, and extensibility of IT systems. Object ori-
entation 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 main-
tainability can be achieved relatively easily with object-oriented concepts.

Example

Without exploring the theoretical background, the following example scenario of a sim-
ple coffee machine shows how object orientation affects the viewing of technical sys-
tems.
Unit 1 17

Introduction to Object-Oriented System Development

In the figure above, a schematic cross-sectional view of a coffee machine is shown.


Translated into the terms of object orientation, the coffee machine can be considered
an “interaction of cooperating objects,” as shown in the figure below. The water tank
object is connected 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.
18 Unit 1

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 drink-
ing water network. The figure below now shows an extended coffee machine as under-
stood 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 drinking 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 connection, 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.
Unit 1 19

Introduction to Object-Oriented System Development

This very simple example illustrates a key aspect of object-oriented systems: The divi-
sion of internal elements into areas that are responsible for a very specific function,
and the interaction among individual objects. The figure above shows the responsibili-
ties of the objects of the coffee machine. Even if the coffee machine cannot be pro-
grammed entirely—because water, coffee and heat are still needed—IT systems are
designed and built according to a similar principle.

Objects of a Coffee Machine

Objects Responsibilities/function

Water tank, later replaced by drinking Water supply


water supply

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

With a clear encapsulation of responsibilities into very specific objects and a clear def- Encapsulation
inition of interfaces, objects can later be interchanged (in our example the water tank The creation of
was interchanged with the drinking water supply) or extended (in our example the objects specifically
extension of the coffee machine happened by adding a clock for time control) without with a view to their
affecting the stability and functionality of the overall system. This in turn simplifies the use in encapsulated
process of quality assurance, since the entire system does not have to be tested again functions and tasks.
but just the affected parts of the system. Other objects can
invoke these specific
functions and tasks
through interfaces.
Summary

Object orientation is an approach to complex systems in which the system is


described as the interaction of cooperating objects.
20 Unit 1

In object-oriented system development, things in the “real” world are replicated


with objects in the “digital” world. Only the values and functions that are relevant
to the purpose of the system are considered. The digitally replicated objects save
values in their attributes and can calculate values in their methods. Object-orien-
ted programs consist of cooperating “digital” objects. The cooperation of objects is
realized through the mutual calling of methods.

The object-oriented development process consists of the phases object-oriented


analysis, object-oriented design, and object-oriented implementation. 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 responsibilities, object
orientation supports development, enhancement, and quality assurance on com-
plex industrial software systems.

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
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.

DL-E-DLBCSOOPJ01-U02
22 Unit 2

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
decided 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 pro-
gramming. Here, Ms. Koch needs to know how to identify objects and what methods to
use, both in representing 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
development, objects in the physical (real) world are replicated as objects in a pro-
gramming language. 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 lan-
guage 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
This is a structure creation of a digital object. Any desired number of objects can be created with a class
that is used to cre- as a basis. All objects created from one class will have the same structure, i.e., the same
ate digital objects attributes and methods. A class is thus roughly comparable to a Word document tem-
which are the central plate, and an object is a Word document that is created from this template. Which
elements in the classes an object-oriented system consists of and what the structure of the required
object-oriented SW classes looks like will be determined in the object-oriented design phase. The starting
development proc- point for the design are the identified and specified requirements. Object-oriented pro-
ess. gramming 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-orien-
ted system then creates the appropriate objects where they are needed, e.g., from data-
base entries or user inputs. The description of the classes guarantees that all objects
that are created based on these 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 func-
tions of the system in the same way.
Unit 2 23

Introduction to Object-Oriented Modeling

The main tasks in the analysis, and later in the design, are the identification and
description 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, dur- This is the result of
ing design, which classes the system should consist of. Possible candidates for classes the object-oriented
must be identified and listed based on the defined problem statement and the analysis, which is
requirements. used for communi-
cation between the
An established procedure for the identification of classes can be described as follows: developers and the
client and/or the
1. Mark all nouns in a problem statement as candidates for classes. users of the system.
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 par-
ticular 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.

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
• game
24 Unit 2

• 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 rectan-
gle.
Unit 2 25

Introduction to Object-Oriented Modeling

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 val-
ues and can be understood as free memory inside of an object. In summary, the values
of all attributes 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.”

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.

Properties of Attributes

Properties of an attribute Description Example

Name Name of the attribute firstname


26 Unit 2

Properties of an attribute Description Example

Data type Defines how the values Date (date)


of the attribute will look String (text)
like, i.e., whether they are Integer (number)
a number, a string, or a
date

Constant (yes/no) Specifies whether the Rounded Pi: 3.1415


value of the attribute
can change or not

Default value Specifies the default 2020-01-01


value of the attribute

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 sce-
nario online shop are added.
Unit 2 27

Introduction to Object-Oriented Modeling

2.4 Methods as Functions of Classes


Methods (also: functions, operations) are dynamic elements of classes. They contain Methods
algorithms, statements, and processing specifications that can be used to create, calcu- These are dynamic
late, modify, and delete values. The results of the methods can be saved in attributes elements of classes
of the class or in newly created objects. Methods are used to describe the behavior of and describe the
objects, i.e., what an object does. Methods can thus be used to program calculations of behavior of classes
values and the application of business rules or specifications in the creation and dele- such as defining
tion of objects. specifications for the
calculation, modifi-
When modeling methods, the elements described in the table below can be defined. cation, and creation
The name, at a minimum, is required in an analysis model. Detailed information on the of attributes and
return value, parameters, and the function of the method can also be added one by objects.
one over the course of the development process.

Properties of Methods

Elements of meth- Description Example


ods

Name Name of the method getLastname()

Parameter Required objects and val- (Date birthdate),


ues that are needed for (String lastname,
processing the method String firstname)
(Integer number1, Inte-
ger number2)

Return value Defines the data type of Date


the object in which the String
result of the method is Integer
stored

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
supply for each of its attributes a method that returns the current value of the attrib-
ute.
28 Unit 2

As shown in the figure above, the methods of a class are modeled in an additional rec-
tangle below the attributes. A class with methods thus consists of three adjacent rec-
tangles: The top rectangle contains the name of the class, the middle rectangle con-
tains 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 devel-
Associations opment process, associations have been defined between classes. In addition, cooper-
These describe ation between objects is only possible when associations have been defined between
dependencies and classes.
relationships
between classes, Typical associations between classes are shown in the following table.
thereby enabling
cooperation between
objects.
Unit 2 29

Introduction to Object-Oriented Modeling

Typical Associations between Classes

Association types Description Example

“has/knows” This type of relationship A policyholder has children.


expresses the fact that one A contract has insurance con-
class “has” or ditions.
“knows” another class. A calendar has months.
A seller knows their custom-
ers.

“consists of” This relationship expresses A car consists of an engine, 4


the relationship in which a wheels, 3 doors, 1 transmis-
class is part of another sion, and 2 seats.
class. It is used when a A house consists of a roof, 23
class is a larger construct windows, 2 doors,
with elements that cannot 6 rooms, and 1 stairwell.
be described using simple
attributes.

“is a” This type of relationship A passenger car is an auto-


expresses the fact that a mobile.
class A is a class B by type, A truck is an automobile.
but it has a more specific A customer is a person.
meaning and may have dif- A book is a product.
ferent attributes and A hedgehog is a mammal.
methods than class B.

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. Addi-
tional information can be added to the relationship, in addition to the continuous line,
as shown in the table below.
30 Unit 2

Multiplicities Quantity specifications for relationships can also be defined using multiplicities (also:
These are quantity cardinalities). This information is shown at the end and at the beginning of a relation-
specifications for ship: The information to the left of “...” represents the lower bound of the quantity spec-
associations ifications and the information on the right of “...” is the upper bound. The table below
between classes. includes an overview of possible quantity specifications.
With multiplicities,
you can specify how
many objects of a
class can be associ-
ated with how many
objects of another
class.
Unit 2 31

Introduction to Object-Oriented Modeling

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.”
32 Unit 2

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.

2.6 Unified Modeling Language (UML)


The application of the concepts (class, object, method, attribute) goes through all pha-
ses of an object-oriented development process. To appropriately document the results
of the phases OOA and OOD, the identified classes and their associations are docu-
mented in a standardized modeling language.

Unified Modeling The Unified Modeling Language (or UML) is a graphical modeling language that was
Language developed in the early 1990s with object orientation. UML now includes 13 different
This is a universal diagram types for modeling different aspects of a system. An overview of the UML dia-
modeling language grams is shown in the figure below. Generally, a distinction is made between diagrams
that is a de facto for modeling structure and modeling behavior. Structure diagrams are used for dia-
global standard for gramming structure, elements, and composition, as well as the interfaces of systems. In
modeling in IT sys- simple terms, structure diagrams are used to model what a system consists of. Behav-
tems. ior diagrams, on the other hand, are used to model what happens in a system.
Unit 2 33

Introduction to Object-Oriented Modeling

Structure diagrams
These are UML struc-
ture diagrams used
for modeling struc-
ture, elements, com-
position, and interfa-
ces of systems (e.g.,
class diagram).

Classes with their attributes, methods, and associations are modeled with the UML
class diagram. The UML class diagram is one of the most commonly used documenta- Class diagram
tion forms in object-oriented system development. All other structure diagrams of the This is a structure
UML are based more or less on the modeling concepts of the class diagram. diagram of UML
which is used for
Object diagrams are a special form of class diagrams. They can be used to model spe- modeling classes,
cific instances of classes. Here, objects whose attributes contain values are modeled. including their
The figure below contrasts the class “Customer” with two concrete objects of the class attributes, methods,
“Customer.” Objects differ from classes in that each object is identifiable with a unique and associations.
ID (here “id1” and “id2”), shown to the left of class name followed by a colon “:” and a
concrete value is shown for each attribute of an object.

All objects of a class have the same attributes, only their values can differ.
34 Unit 2

Object diagram
A structure diagram
of UML which is used
for modeling con-
crete objects, includ-
ing concrete attrib-
ute values as
instances of classes.

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-oriented sys-
tem 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 applica-
ble a default value. Methods, on the other hand, are described by their name,
required parameters, and their return value.

Associations between classes can vary in type; in addition to the “has/knows” rela-
tionship, there are also the “consists of” and “is a” relationships. Individual associ-
ations can be refined by labeling with roles, arrows, and cardinalities.
Unit 2 35

Introduction to Object-Oriented Modeling

UML provides appropriate graphical modeling concepts for standardized represen-


tation of analysis models and the design of object oriented systems. The UML class
diagram and UML object diagram are particularly well suited for modeling struc-
tures. In addition, UML includes various behavior diagrams for modeling the proc-
ess flows of a system.

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
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.

DL-E-DLBCSOOPJ01-U03
38 Unit 3

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 pro-
gramming. Now that she understands that object-oriented systems consist of a set of
cooperating objects, she wants to know how to create classes and objects with the Java
programming 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 ties:
goal of developing
program code that 1. Programming, i.e., production of program code (also: source code, source text, pro-
can be executed as a gram text)
program or program 2. Compiling, i.e., automatic translation of the program code produced into a form that
component after can be executed by a computer
compilation on a 3. Executing a program, i.e., starting and running the generated and compiled program
computer. code to see whether the system performs as expected

While the program code can be written with a simple text editor, software will be nee-
ded 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
This is software that text has been compiled by the compiler, it can be started and executed in a runtime
translates program environment. For many programming languages, the operating system of a PC (e.g., Win-
code into a form dows, Linux, MacOS) provides the runtime environment. Because operating systems
that can be executed have different functions and properties, programs have to be reprogrammed/recom-
by a computer. piled for each operating system. In the example shown below are all the required ele-
ments for development with the C programming language.
Unit 3 39

Programming Classes in Java

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
differs 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 Bytecode
then loaded, started, and executed by the Java runtime environment. Because a Java This is the form a
runtime environment is available for virtually every operating system, a Java program Java program takes
can run on a Linux, Windows, or Mac computer. The figure below provides an overview after it has been
of required elements in development with Java. In contrast to the figure above, here an compiled, which can
additional runtime environment is required to allow execution on different platforms. be executed as a
program from a Java
runtime environ-
ment (JRE).
40 Unit 3

The Java runtime environment (JRE) is required to run a Java program as a user. The
Java virtual machine Java 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
This is an operating it on the operating system being used. The Java class library provides functions that are
system-specific soft- already part of the Java programming language so that commonly used data structures
ware that can run (e.g., lists or strings) can be reused by the programmer, but without having to be reim-
Java programs in plemented each time.
bytecode form on a
computer. To develop software in the Java programming language as a software developer, a Java
software development kit (Java SDK) is required. The Java SDK consists of a Java com-
Java software devel- piler, a Java virtual machine, the Java class library, and other tools.
opment kit (Java
SDK)
This is a basic tool
Tip
for a Java developer.
It includes a com- To facilitate the development process, applications called integrated development
piler, which gener- environments (IDE) are used. For Java, there are for example, Eclipse, NetBeans,
ates bytecode and a IntelliJ, or BlueJ as free IDEs—but there several others available.
JVM for running Java
programs. Your tutor will provide recommendations with download links and instructions so
that you can follow examples and find practical exercises.
Unit 3 41

Programming Classes in Java

3.2 Basic Elements of a Class in Java


A class in the programming language Java has a unique name and can contain attrib-
utes 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 com-
piled 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
minimum are required: the visibility modifier, the class keyword, the name of the class,
and a few curly braces.

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 ele-
ments of the basic structure are described in greater detail:

Basic Elements of a Class in Java

Element of a class Description Example

Visibility modifier Defines the visibility of the class public


for other classes

Keyword for the class Indicates to the Java compiler class


declaration that a Java class is programmed
in the following
42 Unit 3

Element of a class Description Example

Class name Defines the name for the class Customer


and is used as a file name. The
class “Customer” is programmed
in a text file “Customer.java”

Curly brackets Marks the contents of a class { … }


(attributes and methods); every-
thing inside the braces belongs
to a class

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 attrib-
utes 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.
Unit 3 43

Programming Classes in Java

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
• private boolean isPremiumCustomer = false; attribute automati-
• private int quantityOfPurchases= 0; cally when the
object is created is a
The elements of the basic structure are described in greater detail in the table below: default value.

Basic Elements of an Attribute in Java

Element of an attribute Description Example

Visibility modifier Defines the visibility of private


the attribute for other
classes
44 Unit 3

Element of an attribute Description Example

Data type of the attribute Defines the data type of String customer
the attribute and thereby
determines 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).

Attribute name Defines the name for the lastname, firstname, sex
attribute of the class;
each name can only be
assigned once inside a
class.

Default value Defines the initial value =0


of the attribute; this =1
value is assigned to the = false
attribute when creating
an object of the class.

Semicolon Marks the end of the ;


attribute declaration.

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 separa-
tor (e.g., attributeAttribute, nameOfCustomer)
Unit 3 45

Programming Classes in Java

3.4 Methods in Java


With the knowledge acquired thus far we can now program simple classes with attrib-
utes. 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, calcu-
late, modify, and delete the values of attributes.

As previously noted, access to the attributes of an object by other objects is only possi-
ble through methods, but never through a direct access to the attributes of another
class (encapsulation principle). Therefore, methods are also needed to read the values Principle of data
of attributes and make them available to other classes. encapsulation
Here, an object can
In the figure below, a fully implemented class “Customer” is shown in which the ele- never directly access
ments of a method are explained using the method getLastname(). attributes of another
object. Reading or
changing attributes
should only be pos-
sible through meth-
ods.
46 Unit 3

The table below contains the minimal elements that are required in Java for the imple-
mentation of a method.

Basic Elements of a Method in Java

Element of a method Description Example

Visibility modifier Defines the visibility of public


the method for other
classes
Unit 3 47

Programming Classes in Java

Element of a method Description Example

Return data type of the Defines the data type of String customer void
method the object in which the
result of the method is
output after processing
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() getFirst-


method; a method name name()
can only be used more
than once in a class if
the number or
data type of the parame-
ters are different

Parameter list List of required objects (Date birthdate), (String


and their data types lastname, String first-
which are needed for name)
processing the method; (Integer number1, Integer
if no parameters are number2)
defined, the list remains ()
empty
48 Unit 3

Element of a method Description Example

Method body Contains the specific result = number1 + num-


statements for what is ber2;
done when the method return lastname;
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 state-
ments in a method body
are processed in
sequence from the top
down.
If a return data type is
defined for the method,
the last statement of the
method body begins
with the keyword return.

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 method and the parameter list. The return data type is not a part of the signature. Each
and consists of the signature can only occur once in a class since only then can the JRE determine which
name of the method method should be invoked and processed at the runtime of the program. In other
and the parameter words, the name of a method can be assigned more than once in a class as long as the
list. parameter list is different.

Code example 1

Here, the names and the signatures are different:

public void login () {…}


Unit 3 49

Programming Classes in Java

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.
However, 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 Getter and setter
attributes. A getter method returns the value of an attribute. A setter method changes methods
the value of an attribute to the value that is passed as a parameter to the setter These are special
method. methods used for
reading, changing
attributes, and
Example implementing the
principle of data
A class “Customer” fully modeled with getter and setter methods is shown in the figure encapsulation.
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).
50 Unit 3

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 follo-
wing figure the parameter of the setter method setLastname was named with last-
name 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).
Unit 3 51

Programming Classes in Java

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 current
value of lastname to the value “Lange”.
52 Unit 3

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 custo-
mer1.getLastname() it is possible to invoke the specific method getLastname() in
the object customer1. The value of customer1.getLastname() is stored in the invo-
king 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 cus-
tomer1.setLastname(“Lange”) it is possible to invoke the specific method setLast-
name(String name) in the object customer1. With this method invocation,
the “Lange” from another object can be stored as an attribute in the object custo-
mer1.

Method overloading Method overloading means that there are methods in a class with the same name.
This process is used With overloading, i.e., multiple instances of a method with the same name, you have
to implement multi- the ability as developer to define various method behaviors based on the given para-
ple methods with meters.
the same 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—con-
tains an appropriate product as a parameter. The product is an object from the class
“Product.”

public void addToShoppingCart (Product product) {…}


Unit 3 53

Programming Classes in Java

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

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 break-
ing problems down into different classes of a UML class diagram. A Java program like-
wise consists of a combination of different classes that cooperate together through the
invocation of methods. In a Java program, objects are generated from classes at run-
time, 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 genera-
tion 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.

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),
54 Unit 3

• name of method (main), and


• parameter list (String args[]).

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, how-
ever, 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 dia-
gram. A class “OnlineShop” has no attributes, but it does have a main method. The
class “Customer” has four attributes and the particular getter and setter methods.

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 lastname 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.
Unit 3 55

Programming Classes in Java

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
created, i.e., objects of the type customer are created and stored as a variable cus-
tomer1 and customer2 for subsequent use in the main method of OnlineShop.
56 Unit 3

Summary

The Java programming language is a platform-independent programming language.


By using OS-specific Java runtime environments, a Java program can be run on vir-
tually any operating system without customization.

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 imple-
mented method body. The programming in the method body defines what the
method does, or more exactly it defines the statements and processing specifica-
tions.

Access to attributes through another object is usually realized with getter and set-
ter methods. This allows for consistent adherence to the principle of data encapsu-
lation.

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.

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
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.

DL-E-DLBCSOOPJ01-U04
58 Unit 4

4. Java Language Constructs

Case Study
Ms. Koch is now ready to implement the elements of a UML class model in Java pro-
gram 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 attrib-
ute. 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 Primitive data types are used to store logical values (true, false), integers (1, 12, 13131),
numbers or logical floating point numbers (1.123, 21234.1232) and single characters (t, w, f, d). Primitive data
values. 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.

Primitive Data Types in Java

Type of Keyword in Description Examples


saved values Java

Logical val- boolean Can either be true or true


ues false. Other values are false
not allowed.
Unit 4 59

Java Language Constructs

Type of Keyword in Description Examples


saved values Java

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 1102379239
2,147,483,647

long 64-bit value range from 8347829790645,


–9,223,372,036,854,775,808 13, 0, 34879,
to 789234789274
9,223,372,036,854,775,808

Floating float 32-bit value range from 1.87236f (simple


point num- 1.40239846*10–45 to number with deci-
ber 3.40282347*1038 mal point and
appended “f”);
–3.938e12f (
–3.938*1012 with
appended “f”)

double 64-bit value range from 1.87236d (Simple


4.94065645841246544*10– number with deci-
324 mal point and
to appended “d”);
1.79769131486231570*10308 –3.938e120d (
– 3.938*10120 with
appended “d”)

Character char A single Unicode charac- ’A’ (= letter A),


ter. In addition to numer- ’2’ (= numeral 2),
als, letters, and symbols, ’\n’ (= control char-
also includes control acter line break)
characters such as
blanks, tabulator, and line
break.

For integers, the data type int is usually used; smaller data types like byte or short are
only used for programming microcontrollers.
60 Unit 4

String Another frequently used data type is String, which is used for storing strings. String is
This is a data type not a primitive data type, but rather a Java class. However, like a primitive data type,
that is used to store String can be assigned to attributes (and variables). The use of String is described in
strings and in Java the table below. A more detailed discussion of strings is found in the course “Data
has properties of Structures and Java Class Library.”
primitive data types,
although the values
of string are Java String as Data Type for Strings
objects.
Type of saved Keyword in Description Examples
values Java

Strings String Used to save strings of "online",


any length. Is not a "Mr. Koch",
primitive data type. The "What doesn't
class String offers many fit is made to
existing methods for fit",
processing strings. ""

4.2 Variables
Although attributes of objects can be used for saving values in those objects, such
results must still be temporarily saved while processing method bodies which should
not affect the values that are saved in the attributes.

With variables, Java (like all other programming languages) allows concrete values to be
saved in the application memory. These can be used, for example, to temporarily store
results of calculations that are needed as input parameters for other calculations.

As with an attribute, the data type and the name of a variable must be defined to
declare a variable. The declaration (including all subsequent assignments, method
invocations, and calculations) ends with a semicolon “;”. Unlike attributes, however, var-
iables can only be used inside the method body. Therefore they do not require a visi-
bility modifier.

In the top section of the figure below is an example of the declaration of five varia-
bles. Once variables have been declared, they can be used inside the method. This also
means that an actual value cannot be assigned to them until the variables have been
declared.
Unit 4 61

Java Language Constructs

At the bottom of the figure above is an example of the assignment of values to four
variables. The assignment is expressed with the equal sign “=”. To the left of “=” is the
name of the variable, to the right of “=” is the value that the variable should be
assigned. As shown in the figure below, the declaration and assignment of variables
can also be realized in one statement. For example, the program code in the figure
above can be fully replaced with the code shown below.
62 Unit 4

4.3 Operators and Expressions


Operators can be used to calculate and change values that are stored in variables and
attributes. The Java programming language supports a range of arithmetic and logical
Arithmetic operators operators for this purpose. The main arithmetic operators are shown in the table
Operators for exe- below. Generally, the data type of the result of an operator is determined by the oper-
cuting mathematical and with the largest value range.
functions such as
addition, subtrac-
tion, division, and Important Arithmetic Operators
multiplication.
Operation Operator Can be used with data Example
types

Increment; ++ Integers, floating point int a = 3; a+


increases a varia- numbers +;
ble by the value 1 float b = 3f;
b++;

Arithmetic addi- + Integers, floating point int c,d,e;


tion; the result numbers c = 3;
type of the calcu- d = 5;
lation corre- e = c + d;
sponds to that of int x;
the operand with long y,z;
the largest value x = 3;
range y = 4;
(e.g., int+int=int, z = x + y;
int+long=long;)

Arithmetic sub- - Integers, floating point int e = 3;


traction numbers float f = 4;
float g;
g = e – f;

Arithmetic multi- · Integers, floating point int c,d;


plication numbers c = 3;
d = c * 4;
Unit 4 63

Java Language Constructs

Operation Operator Can be used with data Example


types

Arithmetic divi- / Integers: If both oper- int h = 4;


sion; calculates ands are integers, the int i = 3;
quotients of divi- part after the decimal int j;
dend and divisor point is truncated. j = h/i;
Floating point numbers: int o = 4;
If at least one operand is double p = 3;
a floating point number, double q;
the result is a floating q = o/p;
point number and is not
rounded.

Remainder (also: % Integers, floating point int k = 11;


remainder opera- numbers int l = 5;
tor or modulus/ int m;
modulo opera- m = k % l;
tor); calculates
the remainder of
the arithmetic
division

Unlike arithmetic operators, logical operators return a value of true or false for expres- Logical operators
sions. They are therefore often used for managing control structures. The result type of These are operators
logical operators is always boolean. An overview of important logical operators is used to run logical
shown in the table below. functions such as
negotiation, logical
AND, logical OR.
Important Logical Operators

Operation Operator Can be used Example


with data types

Logical comple- ! boolean boolean b1;


ment (negation); boolean b2 = false;
changes the truth b1 = !b2;
value of the oper-
and

Logical AND; && boolean boolean b3;


returns true boolean b4 = true;
when both oper- boolean b5 = true;
ands are true b3 = b4 && b5;
64 Unit 4

Operation Operator Can be used Example


with data types

Logical OR; || boolean boolean b6;


returns true of boolean b7 = false;
one of the two boolean b8 = true;
operands is true b6 = b7 || b8;

Exclusive OR; ^ boolean boolean b9;


returns true if boolean b10 = false;
one operand is boolean b11 = true;
true and one b9 = b10 ^ b11;
operand is false

Relational operators Relational operators compare expressions against each other and return boolean as
These are operators the result type. That is, they either return true or false. Like logical operators, relational
used to run func- operators are commonly used to manage control structures. The table below provides
tions for comparison an overview of frequently used relational operators:
of values and object
references.
Important Relational Operators

Operation Operator
Can Example
be
used
with
data
types

Equality primitive == Primi- int z1, z2;


data types: tive boolean e1;
returns true if data z1 = 3;
the values of the types z2 = 3;
operands are e1 = z1 == z2;
equal.
Reference data Customer customer1, customer2;
types: Returns Refer- boolean e2;
true if the same ence customer1 = new Customer();
object is refer- data customer2 = customer1;
enced in both types e2 = customer1 == customer2;
operands.
Unit 4 65

Java Language Constructs

Operation Operator
Can Example
be
used
with
data
types

Non-equal- != Primi- int z3, z4;


ity Primitive data tive boolean e3;
types: returns data z3 = 4;
true if the values types z4 = 3;
of the operands e3 = z3 != z4;
are not equal.
Reference data Customer customer3, customer4;
types: Returns Refer- boolean e4;
true if the two ence customer3 = new Customer(); cus-
operands contain data tomer4 = new Customer(); e4 = cus-
different referen- types tomer3 != customer4;
ces.

Less than: returns < Inte- int z5, z6;


true if the value gers, boolean e5;
of the operand float- z5 = 4;
on the left is less ing z6 = 5;
than the value of point e5 = z5 < z6;
the operand on num-
the right. bers

Less than or <= Inte- int z5, z6;


equal to: returns gers, boolean e5;
true if the value float- z5 = 4;
of the operand ing z6 = 5;
on the left is less point e5 = z5 <= z6;
than or equal to num-
the value of the bers
operand on the
right.
66 Unit 4

Operation Operator
Can Example
be
used
with
data
types

Greater than: > Inte- int z7, z8;


returns true if gers, boolean e6;
the value of the float- z7 = 6;
operand on the ing z8 = 5;
left is greater point e6 = z7 > z8;
than the value of num-
the operand on bers
the right.

Greater than or >= Inte- int z7, z8;


equal to: returns gers, boolean e6;
true if the value float- z7 = 6;
of the operand ing z8 = 5;
on the left is point e6 = z7 >= z8;
greater than or num-
equal to the bers
value of the oper-
and on the right.

Type comparison: instanceof


Refer- Customer k1;
returns true if ence boolean e7;
the data type of data k1 = new Customer();
the operand on types e7 = k1 instance of Customer;
the left is the
same as the data
type in the oper-
and on the right.

Special equality test operators are the test for equality (==) and the test for non-equal-
ity (!=). In the case of these operators, the operands determine how the comparison is
made. A basic distinction is made between the comparison of primitive data types and
of reference data types. If both operands are primitive data types, then the values of
the operands are compared directly. The figure below shows an example of the compar-
ison of primitive data types where the result (e1) is output in the console. In this case
e1 has the value true.
Unit 4 67

Java Language Constructs

Equality test opera-


tors
These are relational
operators used to
run functions that
test for equality or
non-equality in
which operands
determine whether
values or references
are compared.

Where reference data types need to be compared, the operator “==” does not compare
the actual contents of the objects being compared. Instead, the function only compares
whether both operators reference the same objects, i.e., “point” to the same object. In
the figure below, one newly generated object is assigned to both k3 and k4. In k3 the
reference to the first object “customer” is saved, while in k4 the reference to the second
object “customer” is saved. The comparison of k3 and k4 for “reference equality” thus
returns the value false.

In the figure below the code example from the figure above is modified so that a newly
generated object is no longer assigned to the variable k4. Now, exactly the same value
that is stored in k3 is assigned to variable k4. Since the value of k3 is a reference to an
object of the type “customer,” k4 has exactly the same reference as value as k3 after the
statement k4 = k3. The operation k3 == k4 thus returns the result true.
68 Unit 4

In addition, there is another operator that is frequently used to connect strings


together, i.e., to merge multiple strings into one. The table below shows this operator,
String concatenation which runs the string concatenation.
This is a function of
the data type String
which creates a new Concatenation of Strings
string from two
existing strings Operation Operator Can be used Example
through simply with data
stringing them types
together.

Joining strings + String String s1, s2, s3, s4;


(concatenation): s1 = "Hello";
joining multiple s2 = " ";
strings to form a s3 = "World!";
new string s4 = s1 + s2 + s3;

4.4 Control Structures


The sequence of statements inside of a method body is predetermined by the
sequence of the implemented statements. When the program runs, a method body is
processed from top to bottom. With the implementation of algorithms and business
rules, however, it is often necessary to run concrete statements only when very specific
conditions are present. It is also commonly necessary to run the same statements in
sequence for a set of values, for example, “for all customers” or “for all products.”
Unit 4 69

Java Language Constructs

The controlled repeat execution of statements is enabled using control structures. The Control structures
most important of the Java-supported control structures are These are elements
of a programming
• conditional branches (if-else) and language for condi-
• loops (for, while, do-while). tional or nested exe-
cution of statements.
The classes in the following figure make up the basic structure for the examples in this
learning cycle. The classes are “ShoppingCart” and “Customer” with attributes and in
some cases the relevant accompanying getter and setter methods. (Note: The getter
methods for attributes of the type boolean begin “is” instead of “get.”) What is initially
of interest is the implementation of the method calculateSum(Customer) of the class
“ShoppingCart.”

The conditional branch is used to test the specific place where the program continues Conditional branch
using a condition. The figure below shows an example of the use of conditional This is a control
branches. A price reduction will either be granted or not depending on the status of structure that is
the customer. The structure of a conditional branch in Java appears as shown below: used to execute
statements using
if(condition) { conditions.
Statement1;
}
else {
Statement2;
}
70 Unit 4

The condition must be an expression that can be evaluated to true or false. The State-
ment1 is only executed if the condition is true. In this case, Statement2 is not executed.
Statement2 however is only executed if the condition is false and thus Statement1 was
not executed. The “else part” in conditional branches is optional.
Unit 4 71

Java Language Constructs

The figure above shows the implementation of a method calculateSum(Customer)of the


class “ShoppingCart” that contains a simple conditional branch. In this method, the
sum of a shopping cart is calculated according to the attribute premiumcustomer. If the
customer is a premium customer, then the sum is reduced by 10%. If not, the sum does
not change. With a conditional branch, either the statements in the “if block” or the
statements in the “else block” are executed. Never are both blocks executed. The “else
block” is optional and can also be omitted depending on the problem.

Now the calculation should be extended to include both the number of products in the
shopping cart for premium customers and the redemption of coupons for non-pre-
mium customers. The figure below shows the changed calculation specification.

The correctly modified code example for the method calculateSum(Customer) of the
class “ShoppingCart” is shown in the following figure. The modification was implemen-
ted with nested if-else branches with the else block omitted in the 2nd inner branch
since no discount is granted for non-premium customers without coupon and thus the
sum remains unchanged.
72 Unit 4

Expanded if-else In an expanded if-else branch, not just one condition is tested before the else block is
branch processed, but multiple, mutually exclusive conditions. The structure of an expanded if-
This is a control else branch in Java is shown below:
structure used to
execute statements if(Condition) {
based on multiple, Statement1;
mutually exclusive }
conditions. else if (Condition2) {
Statement2;
}
else {
Statement3;
}

A code example is shown in the figure below. To protect the children, the age rating
should be checked. Here, the customer age is checked, the customer is sorted into an
age class and a message is output in the console. Likewise, with the expanded if-else
branch, just one block is processed. Although for an age of 28 years both the 1st and
the 2nd condition are met, only the statement for the 1st condition is executed.
Unit 4 73

Java Language Constructs

There is also a control structure in Java for complex branches (switch). This structure is
not used in this course, since if-else structures can be used to replicate complex
branches.

Along with branches, loops are another important control structure that is present in Loops
almost every programming language. Loops allow sequential execution of the same They are a control
statements. The number of iterations of the loop is determined by the satisfaction of a structure used for
loop condition (also: running condition, exit condition). There are three different types executing state-
of loops: ments repeatedly.

• while loop,
• do-while loop, and
• for loop.

The while loop tests the loop condition first. If the condition is true, the statements in While loop
the loop are executed. Otherwise, the statements in the loop are skipped. After the This is a pre-checked
statements in the loop are executed, the condition is tested again. If this evaluates to loop. The conditions
false, the loop ends. If the condition evaluates to true, the statements in the loop are are tested before
repeated. The structure of a while loop is shown below: each execution of a
statement.
74 Unit 4

while(condition) {
Statements;
}

The while loop is also called a pre-checked loop, as the condition is already tested
before the first iteration. If it evaluates to false, the entire loop is skipped, i.e., no state-
ment in the loop is executed. The following figure shows an example of a while loop
that calculates all the square numbers for the values 1 to 10 and outputs them in the
console. The counter variable index is initialized outside the loop and is used for con-
trolling the loop: The truth of the condition is tested based on the current value of
index and changes based on that of index during processing of the loop. How many
iterations of the loop actually result is determined by the interaction of the initial value
of index, the loop condition and the statement that changes the value of index.

Do-while loop The do-while loop is a post-checked while loop. The statements in the loop are always
This is a post- executed at least once. Only then is the loop condition tested. If the condition is true,
checked loop; state- the statements in the loop are executed again; if not, the loop ends. The structure of a
ments are executed do-while loop is shown below:
at least 1x and the
condition is tested do {
before a second iter- Statements;
ation. } while (Condition)

The figure below shows the implementation of the calculation of the square numbers
in the figure above using a do-while loop. Both loops behave exactly the same and in
this case can be interchanged with one another.
Unit 4 75

Java Language Constructs

In contrast to the while loop and the do-while loop, in the case of the for loop, the ini- For loop
tialization, condition test, and the changing of counter variables are elements of the The for loop is a pre-
loop head. As in the while loop, the for loop is a pre-checked loop, i.e., the truth of the checked loop in
condition is tested before the initial execution of the loop. which the head, in
addition to the con-
The structure of a for loop can appear as follows: dition, also contains
the statements for
for(initialization; condition; loop increment) { initialization of the
statements; counter variables
} and their incremen-
tation.
The area up to the first semicolon “;” of the head of the loop is reserved for the initiali-
zation of the counter variables. The loop condition is in the area between the first and
second semicolon “;”. The area between the second semicolon and the end bracket “)”
is where the counter variables are changed.

The flow schema of a for loop can be described as follows:

1. Execute statement for initialization


2. Test the condition
3. Evaluate the condition
1. If condition true: Execute all statements in the for loop
2. If condition false: Abort and no execution of statements
4. Execute the statement in the loop increment
5. Continue with #2 (test condition)

The figure below shows a for loop implemented in the program code which calculates
and outputs the square numbers of 1 to 10. This is the same calculation that was run
above with the while loop and the do-while loop. Here it is clear that no control state-
ments of the loop, such as changing the counter variables, are implemented in the
statement block.
76 Unit 4

Control structures can themselves contain control structures in their statement blocks.
Therefore, loops can also be nested with each other. The figure below shows a code
example containing two nested for loops. All of the variables that were declared in
outer control structures are also available in inner control structures. The variable i can
also be accessed inside the second for loop, but statements in the first for loop cannot
access the variable j in the inner for loops.
Unit 4 77

Java Language Constructs

4.5 Packages and Visibility Modifiers


In programming industrial development projects, it is not unusual for code to run to
several hundred Java classes over the course of the project. To support the logical
structuring of classes inside the project and the organization of tasks among the devel-
opment team, the complete group of classes is divided into different packages. Classes Package
with similar functions and classes that are closely dependent on each other are This is an element
assigned to the same packages. The assignment of packages has effects on the storage used for structuring
location of the class and on the access authorizations to methods of other classes. the Java classes of a
development
Packages are comparable to directories on the file system of a computer. Directories project. Java classes
provide a means of structuring files and do not save any information themselves. Each are assigned to
file is saved in just one directory. Directories can contain subdirectories, but files can- packages. Packages
not contain additional files or directories. The same logical relationship underlying can themselves also
directories and files is also applicable with packages and classes. The figure below contain packages.
shows for example the breakdown of classes in Ms. Koch's online shop project. The
package “onlineshop” contains three additional packages “user,” “processing,” and
“products.” In each of these three packages contain classes.
78 Unit 4

The first line of the source text in a Java class always contains the package in which the
class is located. The figure below shows as an example the class “Order” from the pack-
age overview in the figure above. The class declaration comes after the specification of
the package.

Each Java class is saved in a separate file. The storage location of the file is based on
the package of a class. A directory is created for each package of a program. The file
with the Java class must reside in the directory of the package. For the class “Customer”
there must be a file “onlineshop/user/Customer.java” in the package “onlineshop.user.”

Class names must be unique within a package. The complete name of a class (the
“qualified name”) for the Java runtime environment is obtained from the package of the
class and the name of the class. The name under which the class can be addressed
from outside the package is “onlineshop.user.Customer.” At the same time, for example,
there can also be a class "Customer" in a library system that has the name
“library.user.Customer.”

The visibility modifiers were used in introducing the classes, methods, and attributes,
Visibility modifiers but they have not been explained. The visibility modifiers are used to specify the visi-
These elements of bility of classes, attributes and methods and thus the access authorizations of other
Java are used to set classes. There are four visibility modifiers in Java, as shown in the table below. These
the visibility of can be used on the elements class, attribute, and method.
attributes, classes,
and methods to
other classes and Visibility Modifiers
packages.
Description Can be used with Example

The element is visible to Classes, attributes, public class Order {}


all classes in the pro- methods public void calculate-
gram. Sum() {}
Unit 4 79

Java Language Constructs

Description Can be used with Example

The element is only visi- Classes, attributes, class Order {}


ble in the same package. methods void calculate Sum() {}

The element is only visi- Attributes, methods protected void calcula-


ble in the same package teSum() {}
or derived classes. protected int quantity-
Product;

The element is only visi- Attributes, methods private void calculate-


ble for elements of the Sum() {}
same class. private int quantity-
Product;

Although in Java the developer has the option to determine the visibilities of attributes
so that direct access from other classes is possible, attributes should always be
assigned the visibility “private” except in clearly justified cases.

Summary

With primitive data types, simple standard data types can be used in Java to store
logical values (true, false), integers (1, 12, 13131), floating point numbers (1.123,
21234.1232) and single characters (t, w, f, d). Although the String data type for storing
strings is a very commonly used data type, it is not a primitive data type.

With variables, concrete values can be stored in the application memory so that
temporary results of calculations can be stored temporarily while processing a
method.

Arithmetic operators (+, -, *,/, %, ++) and logical (!, &&, ||, ^) operators can be used
to calculate and change values that are stored in variables and attributes. Rela-
tional operators (==, !=, <, <=, >, >=, instanceof) compare expressions with each other
and return a result of true or false. With the equality operators (==, !=) the operands
determine whether the values of primitive data types or object references of refer-
ence data types are compared.

With conditional branches (if-else), the execution of statements can be made con-
tingent on conditions and in this instance conditional branches can also be nested.

Loops are used for repeated execution of the statements in sequence, where the
number of iterations is determined by the truth of the loop condition. A distinction
is made between pre-checked loops (while, for) and post-checked loops (do-while).
80 Unit 4

For logical structuring of the classes in a project, the entire set of classes is divided
into different packages where each class is assigned to one package and packages
can contain additional packages. The visibility modifiers (private, “”, protected, pub-
lic) are used to specify the visibility of classes, attributes and methods and thus the
access authorizations of other classes.

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
Unit 5
Inheritance

STUDY GOALS

On completion of this unit, you will have learned …

… for what purpose inheritance is used in object-oriented systems.

… how inheritance is expressed in UML class diagrams.

… the difference between a superclass and subclass.

… how inheritance between Java classes is expressed.

… what is meant by overriding inherited attributes and methods.

DL-E-DLBCSOOPJ01-U05
82 Unit 5

5. Inheritance

Case Study
Ms. Koch has already implemented a few classes. During programming, she notices that
for some of the classes she has written down the same attributes and methods.

She checks in her class model for anything unusual about these classes. She notices
that she has assigned “is a” relationships for the class “Product.”

Now Ms. Koch considers how these two facts fit together and wonders how she might
model this concept more precisely and then program it.
Unit 5 83

Inheritance

5.1 Modeling and Inheritance in the Class Diagram


If you compare the attributes of the classes “Book,” “Music product,” “Game,” and “Film,”
it becomes clear that some of them appear in all of the classes and some just in a few
of them. The attributes “manufacturer,” “title,” and “product number” were identified as
important attributes for all four classes: All four classes share these attributes. The
attribute “author,” however, is only important in the classes “Book” and “Game,” while
the attributes “Performer” and “Director” are each present in just one class.

The attributes that all classes share can be combined into what is called superclass.
Using the “is a” relationship, these attributes are passed to the associated classes and
then do not have to be executed again there.

UML class diagrams have their own notation for the “is a” relationship. A line is drawn
between two classes and, at the end, a closed, hollow arrowhead is drawn.

The “is a” relationship is an important concept in object orientation and is classified as “is a” relationship
an inheritance relationship. This relationship expresses that a class A can be viewed as This relationship
similar to a different class B. In the example of Ms. Koch it means that the classes expresses the fact
“Book,” “Music product,” “Game,” and “Film” can all be considered products; books, that a class is a spe-
music products, games, and films are products. This is the difference from the normal cial type of another
“knows” relationship between classes: The “is a” relationship expresses that a class is a class.
special type of another class.
84 Unit 5

Superclass The class “Product” in the example is classified as a superclass and the other classes
This is the designa- are classified as “subclasses.” “Base class” is another term that is commonly used for
tion for a class from superclass and subclass is frequently also called a “derived class.” A subclass is also
which other classes described as being derived from a superclass.
are derived.
With inheritance, all of the attributes of the superclass are shared with the subclasses.
Thus, a “book” also has a “manufacturer,” since the “book” is a “product” and this has a
“manufacturer.” A “game” also has a “title” as it inherits this attribute from “product.”

Subclass The subclasses are a more specific type of superclass. They have all the attributes of
A subclass is derived the superclass, but in addition define other attributes that are important for their own
from a superclass description. For the description of a book, the author is important, but for the sale of
and inherits its the book “as a product” manufacturer, title, and product number are sufficient.
attributes and meth-
ods. It specializes a So, the inheritance relationship is used to model more specific classes of another class.
superclass by imple- In the example, the class “Product” is modeled to speak generally about elements of an
menting an order. Here, it is not a question of the exact properties of the actual product, but it is
improved functional- important to know for the display on the website whether a particular product is a
ity with additional book or another type of product. On the particular product page the specific properties
attributes and meth- of a product are important, e.g., the author of a book or the performer of a music prod-
ods. uct.
Unit 5 85

Inheritance

Here, you can see very clearly how inheritance helps in modeling: You can generally
express that each product can be displayed on its own page. But how exactly this page
should appear is determined based on the actual type of product. Different properties
will be displayed for a book than for a game. Inheritance is what allows information to Inheritance
be conveyed about things either generally or specifically while avoiding redundancy. This type of relation-
ship enables the
The inheritance relationship is transitive, meaning the attributes of an ancestor class abstraction of com-
are passed down to all child classes. A “Product” is also a further specialization of the mon attributes in a
class “Book,” since “Book” is itself a “Product.” In the example shown in the figure superclass, thereby
below, “non-fiction book” inherits all the attributes from both “product” and “book.” reducing repetition
in design.
86 Unit 5

With inheritance, it is not simply the attributes of the superclass that are shared with
the subclasses, but rather methods and associations of the superclass are shared as
well. In this way, not only is the form of the superclass inherited, but also its behavior
and its use.
Unit 5 87

Inheritance

Objects of subclasses have the same methods as objects of superclasses and can be
addressed in the same way. With the inherited associations, it becomes clear where the
objects of subclasses can be used and how they are used in these places.

Object-oriented systems are structured using inheritance. Shared attributes of previ-


ously defined classes are combined by defining superclasses. Changes to the super-
class are shared with all derived classes. When an attribute is added to the superclass,
then all derived classes will also have the new attribute; if an attribute is removed from
the superclass, it will also no longer be available in the subclasses. Through the deriva-
tion from an existing superclass, a new class is specialized for a particular application.
The attributes and methods of the superclass are not repeated to avoid redundancy
and improve the clarity of the system design in the model.

By grouping shared features together and deriving specialized classes, there is a possi-
bility of new classes being introduced to the model that have not been identified dur-
ing the analysis phase. This is not a problem as long as it ensures that the model is of
a manageable scope.

In general it is common for a subclass to be derived from just one superclass. In the
case of multiple superclasses, a subclass would inherit the union of the attributes and
methods of all the superclasses. In that case, it is possible to have the same names
assigned in two different superclasses but with different meanings. But this conflict
often results in a model that is more difficult to understand and in modeling errors. In
addition, it is possible that the programming language in which the modeled system is
implemented will not support multiple inheritances. Java, for example, does not sup-
port it.
88 Unit 5

5.2 Programming Inheritance in Java


In Java, inheritance is implemented with a new keyword in the declaration of a class.
Unlike the previously introduced concepts “derivation” or “specialization,” in Java the
Extension concept is called extension. A subclass “extends” a superclass when it defines, or
In Java, the concept modifies, new attributes and methods; thus, the keyword is extends.
of extension is used
for the implementa- The inheritance relationship in Java starts from the derived class, just like the direction
tion of inheritance. A of the association arrow in UML class diagrams. In Java inheritance is expressed by stat-
subclass specializes ing in the class declaration of the subclass which superclass it is being derived from.
its superclass with
new and adapted The subclass inherits all the attributes and methods of the superclass. An exception
functionality. are attributes and methods that have been declared private in the superclass. These
are also unavailable in a subclass. But otherwise, inherited attributes and methods
retain their visibility. Attributes and methods are declared public and remain public.

The figure below shows an extended example. The class “Book” is derived from the
class “Product.” An additional attribute named author is defined and appropriate getter
and setter methods are implemented for it.
Unit 5 89

Inheritance

In addition to instantiating a book object, the inherited attributes and methods can be
used like normal instance attributes and methods. The inherited attributes receive the
values from the superclass. When invoking inherited methods, the implementations
from the superclass are used.
90 Unit 5

In the figure above, a book object is generated and both the new attribute and the
inherited attributes are set using the inherited getter and setter methods. The book
object can thus be used like a product object because it has the same attributes and
methods as a product.

It is also possible to declare a variable of the type product and assign a book object to
Assignment compati- it. This is called assignment compatibility: Each book is a product and can be handled
bility as such.
This means that a
variable of the type But in reverse, there is no such compatibility: Not every product is a book. Looking
of a superclass can again at the class diagram “Equal attributes are combined in the superclass,” the differ-
also be assigned ence is clear. The class “Book” declares a new attribute that is not present in the prod-
subclass objects. uct. The instantiated product object thus cannot be treated like a book in the event
that someone wishes to access the new attribute.
Unit 5 91

Inheritance

In considering assignment compatibility, it is necessary to consider another issue: The


type of a variable decides which attributes and methods can be invoked. In the figure
below, a variable product of the type Product is declared and a new instance of book is
assigned to it. Only the methods of the class “Product” can then be invoked on the vari-
able product. The invocation of setAuthor is returned as an error by the compiler
because the method in the class “Product” was not defined in the class “Product.”
92 Unit 5

The assignment compatibility is used to ensure the loosest possible coupling of indi-
vidual classes in large software systems. If a list of manufacturers is created through
the total product quantity, for example, it does not matter whether the products are
books, games or films. The solution can thus be implemented independently of the
concrete specifications by focusing on the functionalities declared in the class “Prod-
uct.” Thus, additional subclasses of Product can be created during implementation—for
example, for toy—without the loop that compiles the manufacturer list having to be
modified.

In the figure below, a possible version of a loop is shown that is used to determine the
manufacturer for all the products on a product list and add them to the manufacturer
list. The loop will work regardless of whether the product list contains only books, films,
or a variety of objects from the different subclasses of products.

Although subclasses inherit the attributes and methods of the superclass, they are
strictly tied to the implementation. For example, the method getDescription defined in
the class “Product” outputs an incomplete description for the subclasses. The books
are missing the author, the films are missing the director, etc. A correct implementation
of getDescription would need to include these attributes in the output, but this can
only be done in the subclasses. The class “Product” knows nothing of the additional
attributes of the subclasses that also have to be output. The subclasses thus have to
adapt the implementation of the inherited method getDescription for their purposes;
Overriding this process is called overriding.
The process of
implementing an Methods can be overridden in subclasses by creating a method with the same signa-
inherited method is ture and implementing a new method body.
called overriding.
Unit 5 93

Inheritance

If an instance of the subclass is generated and inherited attributes or methods are


accessed, then the overridden versions are selected. The instance determines which
implementation is executed. In the figure below, an instance of the class “Book” is gen-
erated and is assigned to the variable. After setting the attributes, the overridden
method getDescription is invoked. This method outputs a complete description that
includes the author.

When overriding attributes and methods, the original implementation from the super-
class is overridden by the new implementation. It is possible, however, to access the
existing implementation in the superclass. You can utilize this option by using the Java
keyword super. With super, the superclass is addressed and its attributes and methods
94 Unit 5

can be accessed. Because each subclass can only have one superclass, the use of super
includes a clear definition of which class is intended. super goes up one level in the
inheritance hierarchy and selects the implementation there.

super can be used to extend implementations from the superclass. First, the existing
implementation is invoked and then additional statements that are important for the
functionality in the subclass are implemented. The implementation of the overridden
method shown in “Invoking an overridden method” can also be implemented (e.g., as
shown in the figure below). First, super is used to invoke the implementation from the
superclass and then additional attributes are added to the result.
Unit 5 95

Inheritance

Summary

The concept of inheritance allows the functionality of existing classes to be used in


new classes and for special applications to be adapted. With inheritance, a sub-
class is derived from a superclass. The subclass inherits the visible attributes and
methods of the superclass.

In UML class diagrams, the inheritance relationship is expressed by means of an


association line with an empty arrowhead at the end pointing to the superclass.
The new attributes and methods are now listed in the subclasses. The inherited
attributes and methods are not repeated. Associations of the superclass are also
inherited by the subclasses. The inheritance relationship is transitive and allows
the passing of attributes and methods over multiple hierarchy levels.

In Java, inheritance is expressed with the keyword extends. The same attributes and
methods are available in the instances of the derived classes as in the instances of
the superclass and can be used in exactly the same way as their own attributes and
methods. Therefore, instances of derived classes can also be assigned to variables,
which have been declared of the type of the superclass. This is called assignment
compatibility.

Inherited attributes and methods can be redefined in the subclass. This is called
overriding. The keyword super is used to access the overridden version of the
attributes and methods of the superclass.
96 Unit 5

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
Unit 6
Important Object-Oriented Concepts

STUDY GOALS

On completion of this unit, you will have learned …

… how to use abstract classes to set limits on which classes instances can be generated
from.

… how to use abstract methods to determine which methods subclasses have to


implement.

… what the term polymorphism means and what advantages it offers for object-oriented
systems.

… how to define static attributes with the same values for all instances of a class.

… how to define static methods of classes that can be invoked without having to create
object instances.

DL-E-DLBCSOOPJ01-U06
98 Unit 6

6. Important Object-Oriented Concepts

Case Study
Ms. Koch discusses the project status with her customer Mr. Lange. She reports how she
has implemented the classes “Book,” “Music product,” “Game,” and “Film” as subclasses
of “Product.” Mr. Lange takes particular interest when Ms. Koch explains how the sub-
classes override a method of the superclass in order to create a more detailed descrip-
tion of themselves. Mr. Lange has the idea of extending this functionality for a special
feature: He would like for customers to be able to send their product request via Twit-
ter.

Ms. Koch agrees and considers how she can accommodate this requirement in her sys-
tem. Since such a message only has a limited number of characters available, the rele-
vant subclasses should generate an extra-compact description. Ms. Koch could imple-
ment an appropriate method again in the class “Product” and override it in the
subclasses. However, each subclass must override the method in order to truly bring
together only the most essential elements. Ms. Koch wonders how she can force sub-
classes to override a specific method.

She comes to the conclusion that, on account of the new feature, it should no longer
be possible to create objects from the class “Product”; each product should describe
itself concisely through the Twitter method. But Ms. Koch notices that something like
that would not make sense for a product object without a concrete assignment of
which type of product it is. She thinks that, in fact, it should still be possible to prohibit
the generation of objects of certain classes.

6.1 Abstract Classes


In modeling, Ms. Koch uses the class “Product” to combine the classes “Book,” “Music
product,” “Game,” and “Film.” As she correctly observed, it makes little sense to generate
an instance of the class “Product.” Although a product object has a title, a manufacturer
and a product number, this is not yet sufficient to identify what kind of product it is.
Without this information it is difficult to use the product appropriately in the system.
How the product page should appear in the online system, for example, is not speci-
fied. The type of product is also an essential element for a concise description.
Unit 6 99

Important Object-Oriented Concepts

In the example, the class “Product” is thus primarily used for modeling and structuring
the system being developed, but no concrete instances should be generated from it. It
should only be possible to use the different types of products in a consistent way.

The class “Product” is also called an abstract class. With this, it is explicitly expressed Abstract class
that no instances of this class can be generated. Specific details are implemented in This is a class of
the derived subclasses. which instances can-
not be created,
In UML, abstract classes are designated, with the word abstract in curly braces. Alter- where common fea-
nately, the class name can be set in cursive font. tures are grouped
together and an
interface that must
be supported by its
derived datasets is
defined.

To implement abstract classes in Java, the keyword abstract is used. Once a class is
designed as abstract, instances cannot be created from it. Otherwise they are struc-
tured like normal classes.
100 Unit 6

They can define attributes and assign values to them, as well as define and implement
methods. Derived classes inherit these attributes and methods as normal.

In the figure below, the class “Product” is made into an abstract class by adding the
keyword abstract in the class declaration. Nothing has to be changed in the other dec-
larations. But if you now try to create instances of this class, the compiler will return an
error.

With this step, Ms. Koch can now prevent product objects from being created in her sys-
tem.

Not only classes, but also methods of a class can be designated as abstract. An
Abstract method abstract method has a signature, but no implementation. Just as there can be no con-
This method has a crete instances of abstract classes, abstract methods cannot define method bodies. As
signature but no a result, a class with one or more abstract methods is not complete. Thus, if a class
method body and it defines at least one abstract method, it must also be declared abstract in the class
defines the function- declaration. The abstract method must then be implemented in a subclass through
ality that must be overriding.
implemented in sub-
classes. Abstract methods must be implemented by concrete subclasses. Ms. Koch can use this
to require the implementation of the Twitter method for the subclasses of “Product”. In
the figure below, the class “Product” is extended by adding the method getTwitterDe-
scription(). This method is marked as abstract and there is no method body.
Unit 6 101

Important Object-Oriented Concepts

This method must now be implemented in a subclass of “Product.” This works exactly
the same as the override of an inherited method. In the figure below, the abstract
method is implemented in the class “Book.”

The implementation of an inherited abstract method in a subclass is forced by the


compiler. The only possibility for not implementing an abstract method in a direct sub-
class is to designate it as abstract again there. However, this results in this subclass
becoming an abstract class and the responsibility for implementation being delegated
to other subclasses.

It is possible to declare variables of the type of an abstract class, but, since no objects
can be created from this abstract class, the assigned value of the variable thus
declared must be an object of a derived class.
102 Unit 6

In the example below, an attempt is first made to create an object of the “Product” with
new Product(), but this is not allowed by the Java compiler. Then a variable of the type
“Product” is declared and a new instance of the class book is assigned to it; this is
allowed because assignment compatibility exists through the inheritance relationship
between “Book” and “Product.”

With the concepts of abstract classes and methods, Ms. Koch has been able to prevent
the creation of concrete product objects and to make implementation of a Twitter
description mandatory for all subclasses.

6.2 Polymorphism
Ms. Koch is happy to avoid redundant definitions in her system using inheritance and
to require the implementation of important methods using abstract methods. She is
implementing specialized functionality like the creation of brief descriptions where
they are appropriate, such as in special subclasses. But the question arises of which
object-oriented concept explains the fact that the correct implementation is always
used even though she sometimes just declares her variables of the type “Product.”

The object-oriented concept that explains this phenomenon is polymorphism. Poly-


morphism simply means diversity. In object-oriented systems, it refers to the fact that a
declared variable of the type of a particular class can also accept instances of the sub-
classes. A variable can thus appear in a diverse set of specific forms. Using inheritance
relationships, the figure below shows that behind a variable of the class “Product”
there may also be instances of “Book,” “Music product,” “Game,” and “Film.”
Unit 6 103

Important Object-Oriented Concepts

Polymorphism
This means that
objects of different
classes can be
assigned to a varia-
ble when the classes
have an inheritance
relationship with
each other. This way,
it is possible to call
different method
implementations
through the same
variable based on
which object is
assigned to the vari-
ables of runtime.

The individual subclasses can override methods in order to specialize behavior. In the
example system, we generally speak of products and demand very specific require-
ments—such as, for example, outputting a description text—from them. However, the
implementation of this requirement differs from subclass to subclass. Polymorphism
allows all instances of subclasses to be treated as products as well as access the rele-
vant special implementation of methods.

Just as the type of a variable decides which methods can be invoked, the instance of a
class decides which implementation of these methods will be executed. The figure
below illustrates this process using the example of the invocation the method getDe-
scription for a variable of the type “Product.”
104 Unit 6

The concept of polymorphism allows methods to be invoked by objects without having


to know which specific subclass these objects belong to. It is important for the objects
to implement the functionality that is needed.

But it is also possible to check which class an instance belongs to at runtime. The
instanceof operator can be used to run a test of class membership, but this will neu-
tralize the advantages of polymorphism. Here, you can test for very specific class mem-
bership but no longer work with any subclass instances you like.

In the following example, the instanceof operator is used to test the past object for
membership in the class “Book.” If this is the case, special preparations can be made
for processing a book object; nevertheless, it is worth reflecting on whether these prep-
arations can also be made from the book object to avoid querying the specific class.
Unit 6 105

Important Object-Oriented Concepts

With polymorphism, Ms. Koch can address different types of products in her system
through a common interface and at the same time access their special implementa-
tions. She thus obtains an appropriate description of each product when she calls the
method getDescription.

6.3 Static Attributes and Methods


During the implementation of her system, Ms. Koch notices that she always uses the
same sign for the separation of attribute values. Because she fears she may have to
change the sign again later, she would like to introduce a variable for it. This variable
should apply to all products, and therefore Ms. Koch first considers declaring them as
an attribute of the class “Product.” However, she notices that in that case she would
first have to create an object of “product” to access the attribute. The question is
whether there is a better alternative.

Class variables are also called static attributes since they are not bound to an object Class variables
but are already available from the time a class exists. Static attributes apply to all These attributes are
instances of a class. Their value is shared by all instances of the class. Class variables the same for all
are declared with the keyword static. instances of a class
and are addressed
The following figure shows how Ms. Koch declares the class variable descriptionSepara- through the class
tor as a static attribute of the class “Product.” She can then access this attribute name.
through the class and does not have to create an object in advance.
106 Unit 6

When the value of the static attribute is changed, then it changes for all the objects of
the class and the subclasses.

In addition to attributes, methods can also be declared static. These methods are also
independent of the existence of a concrete object and are invoked through the class.

Ms. Koch uses a static method to implement a test for the validity of a given product
number. The test can thus be performed before a concrete product object has been
created. The figure below shows the declaration and use of the static method.
Unit 6 107

Important Object-Oriented Concepts

Because static methods can also be invoked without the existence of objects of the
particular class, instance methods or variables cannot be accessed in the method body.

Static attributes are often found in the Java class library with the definition of con-
stants. For example, the number Pi and Euler's number e are defined as static attrib-
utes of the class “Math” (see Oracle 2013b).
108 Unit 6

Examples of static methods are also found in the class “Math.” The results of the meth-
ods sin, cos, log can be calculated without having to access the internal state of an
object. Therefore, there is no need to create an instance of “Math” before these meth-
ods are used. The output of the methods is strictly determined by the values of the
parameters alone.

Summary

Abstract classes and methods are declared using the keyword abstract. Abstract
classes are classes of which instances cannot be created. They are concretized in
subclasses through inheritance and are used primarily to combine shared attrib-
utes and methods of subclasses. Abstract methods are methods that have no
method body; they are used to force a subclass to override this method with a con-
crete implementation. As soon as a class declares an abstract method, the entire
class must be declared as abstract.

Polymorphism means diversity and allows instances of subclasses of a certain class


to also be assigned to a variable of that class. The type of variable defines which
attributes and methods can be accessed, but which concrete implementation is
used is determined at runtime. The type of instance decides which attribute value
is returned and which method implementation is executed.

Static attributes and methods are declared using the keyword static. They apply to
all instances of a class. They are accessed with the class name and no concrete
object of the class has to be created beforehand. Static attributes are often used
for the definition of constants. Static methods cannot access instance variables or
methods and they frequently implement functions whose results depend only on
the input parameters.

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
Unit 7
Constructors for Generating Objects

STUDY GOALS

On completion of this unit, you will have learned …

… what a standard constructor is and how to create objects using constructors.

… how to use different constructors to create objects with specially tailored defaults.

… what issues related to inheritance need to be considered when using constructors.

DL-E-DLBCSOOPJ01-U07
110 Unit 7

7. Constructors for Generating Objects

Case Study
When creating objects, Ms. Koch has always relied on setting their attributes with getter
and setter methods individually. Occasionally she would encounter errors in doing this,
for example when she forgot to set attributes. In reading about this issue, Ms. Koch dis-
covered the option to define constructors. Now, she can define a standard constructor
and thus specify exactly how objects of the class customer can be created. To allow
room to respond flexibly to different situations, Ms. Koch can also define different con-
structors by overloading the standard constructor. She is also familiar with the process-
ing sequence of the constructors, in case the generated objects are in an inheritance
hierarchy. This is relevant, for example, in cases where a reduced minimum order value
should be set for premium customers of the online shop.

7.1 The Standard Constructor


Ms. Koch now understands what object-oriented programming is about and what
resources Java offers to implement its concepts. Along the way she also learned how to
create objects in Java using the new operator, although she does not entirely under-
stand the details of this statement. She learns that the creation of objects is one of the
main tasks in Java programming. For that reason, she wants to focus on it in greater
detail. In particular, Ms. Koch wants to learn how to influence the process of creation.
So she decides to start with the main() method from the online shop she's already
familiar with. It illustrates the use of the already familiar new operator:
Unit 7 111

Constructors for Generating Objects

As the name suggests, the new operator has the purpose of creating a new object for a New operator
particular class (here: “Customer” and “ShoppingCart”). What is not yet clear is how the An operator creates
creation of such an object is defined and what exactly happens when you invoke the a new object for a
new operator. The standard constructor is used so that you know what values are particular class. The
assigned to the attributes of a customer object and how to influence this definition. It constructor is
is invoked through the new operator and returns the generated object as the result. invoked for this pur-
pose.
You can imagine the standard constructor as a special kind of method that can only
exist once per class. Aside from a few restrictions, the syntax is very similar to a normal Standard constructor
method (see figure below). This is a special
method for creating
objects of a class.

The following rules apply for the definition of the standard constructor: The name of
the constructor must always be the same as the class (here: “Customer”); it has no
return type and the visibility should always be public so that other classes can create
an object of this class via new operator; unlike the overloaded constructors that will be
discussed in the next section, the standard constructor has no parameters, but usually
just two tasks instead:
112 Unit 7

1. Adapting the default values for primitive data types


2. Creating non-primitive attributes (objects)

In the example, the result of the standard constructor is, first of all, that the minimum
order value is not set by default to 0, but to 10 euros. Secondly, a new, empty object is
created for the non-primitive attribute shoppingcart.

If both of the above tasks are not necessary for a particular class, then the definition of
a standard constructor is likewise not required and it can be omitted. In this case, an
Empty standard con- empty standard constructor is implicitly added by the Java compiler. This means that
structor even though the constructor is not visible in the source text, it can still be invoked with
If a constructor is the new operator and it can thus create an object.
not defined, the
compiler adds an When using constructors generally, it should be noted that unneeded objects are auto-
empty standard con- matically deleted by the Java runtime environment. Here, the term “garbage collection”
structor. or automatic memory management is used. That is, unlike other programming lan-
guages like C/C++ or Objective C, it is normally not necessary to explicitly destroy
Garbage collection objects using a programming statement. The automatic memory management that is
This is a concept in integrated in Java works very well even when programming with high memory require-
the Java program- ments. But when there is still a need to free up memory, the garbage collector can be
ming language for invoked with the statement System.gc().
automatic memory
management.

7.2 Overloading Constructors


In practice, it is common to assign values to objects immediately after they are created.
For example, Ms. Koch imagines that a new visitor to the online shop may want to cre-
ate a new customer account. The information that is filled in on the online form (see
figure below) should be saved next in a new customer object. For this Ms. Koch needs a
new method with the appropriate parameters that will return a customer object (see
class diagram).
Unit 7 113

Constructors for Generating Objects

With the resources that we know thus far, this can be programmed as follows:
114 Unit 7

The more attributes a class has, the greater the programming time and effort it requires
and the more the program grows in size as similar statements are added. It can then be
very difficult to determine whether all needed attributes have actually been set or an
attribute has perhaps been forgotten. In such cases, it is possible to overload the
Overloaded standard standard constructor. This means that a second constructor can be defined in addition
constructor to the standard constructor. This constructor, unlike the standard constructor, has a
Such a constructor is parameter list. With the parameter list, it is now possible to determine precisely which
used to initialize an attributes should be used to fill the object with information at runtime. The value
object with values assignment no longer has to be manually performed in each affected place using setter
that are only deter- methods, but just once in the new constructor. Using the familiar example, the figure
mined at runtime so below shows how the standard constructor can be overloaded.
that, in contrast to
the standard con-
structor, it defines a
parameter list.

When invoking the constructor, Ms. Koch observes that not much has changed in com-
parison to the invocation of the standard constructor. The new operator will of course
be used again in this case and the class name will be declared. But, in invoking the
overloaded constructor, the parameters in the round brackets are also declared (see
figure below). Compared to the example in “Common allocation of the object attributes
Unit 7 115

Constructors for Generating Objects

by setter methods”, the program code is now significantly tidier. In addition, an error
message of the compiler would also prevent Ms. Koch from forgetting an attribute in
the parameter list.

An additional problem arises when objects of a class need to be initialized with differ-
ent combinations of attributes depending on the original situation. For example, in the
online shop there is an additional mask in addition to the input mask described above
(see figure below).

Unlike the first mask, this mask is used only for managing the most important attrib-
utes (e.g., in a quicker, provisional data collection). In such cases, it is necessary to
define an appropriate constructor for each combination of available information.
Because of overloading, it is possible in Java to program any desired number of con-
116 Unit 7

structors provided the parameter lists are different. In the figure below, we show how
the preceding example can be enhanced with an additional constructor. It makes a lot
of sense to have the constructors invoke each other to avoid double code and to
improve serviceability. Invoking other constructors within overloaded constructors can
be carried out using the statement this(). This statement must always be in the first
position, otherwise the compiler will return an error message.

The processing sequence in calling such a chain of overloaded constructors can be


illustrated in the following example: If a program invokes the second overloaded con-
structor to create a new object with all attributes, then the first overloaded is invoked
first. The required parameters firstname and lastname are passed to it. The first con-
structor in turn invokes the standard constructor first, of course without parameters. As
soon as the standard constructor has specified the minimum order value and has cre-
ated a new object for the shopping cart, the program continues from the first construc-
tor. First and last name are then set there. The information for this comes from the
parameter list of the second constructor. In the final step, the program returns to the
second constructor and ensures that other attributes, like the sex and birthdate, are
set. Constructors are also suitable for creating copies of similar objects.

If in the online shop, for example, a backup copy of a customer should be created, you
Copy constructor can use “copy constructor” (see figure below), which will then be called as follows:
This is used for clon-
ing objects. It can be Customer newCustomerObject = new Customer(existingCustomerObject);
programmed so that
Unit 7 117

Constructors for Generating Objects

a deep copy (all ref-


erence data types
are also cloned) or a
shallow copy (just
primitive data types
and strings are
cloned) is created.

To highlight the function of a copy constructor as much as possible, we have not used a
chain of constructors in this case. Of course you can also use the second constructor
from the figure on the previous page to avoid redundant code, but do not forget to add
the minimum order value. Since, if a customer has an individual minimum order value
that is different by 10 euros, an external program or another programmer has to be
able to rely on it being a “genuine” copy constructor.

In this context, the assignment shoppingcart = original.shoppingcart should also be


reconsidered since it means that both customer objects (the original and the clone)
have the same shopping cart, since their references that are saved in shoppingcart
refer to the same shopping cart object. This is also called a shallow copy, since only the
object itself is cloned, but not the objects referenced by it. However, if in the copy con-
structor in the figure above in the assignment of shoppingcart you invoked a copy con-
structor for the class “ShoppingCart,” then you would have a cloned customer with a
cloned shopping cart:

shoppingcart = new ShoppingCart(original.shoppingcart)

This would be an example of a deep copy, since reference data types are also cloned by
creating new objects and it is not just the references being copied.

7.3 Constructors and Inheritance


Where classes are in an inheritance hierarchy, it may be necessary in certain cases to
access the constructor of the superclass, assuming a distinction is made in the online
shop between premium customers and normal customers. Unlike for general custom-
ers, for premium customers there is a reduced minimum order value (see figure below).
118 Unit 7

In the Java programming language, it is possible to invoke the constructor of the super-
super() class. Here, the keyword super() is used (see figure below). As with the keyword this,
This keyword can be super can be invoked with or without parameters. In the first case, an overloaded con-
used to invoke the structor is searched and in the second case the standard constructor of the superclass
constructor of the is invoked. Constructors are also suitable for creating copies of similar objects.
superclass.
Unit 7 119

Constructors for Generating Objects

Summary

Constructors allow a programmer to determine the rules for creating objects. By


overriding the standard constructor, the default values for primitive data types can
be modified. If a class contains attributes with complex data types, constructors
can ensure that instances of such attributes are always present.

In the event that objects of a class should be created in a different way depending
on the situation, multiple constructors can also be defined.

The different parameter list can then be used to differentiate which constructor is
meant in an invocation. To avoid extra work due to redundant code, constructors
can be nested, i.e., they can invoke one other and set just the number of additional
parameters themselves.

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
Unit 8
Handling Exceptions with Exceptions

STUDY GOALS

On completion of this unit, you will have learned …

… when exception handling in Java makes sense or is necessary.

… what means Java has at its disposal for catching, throwing, or handling exceptions.

… in what cases these means are not sufficient.

… how you can program your own exceptions to cover such cases.

DL-E-DLBCSOOPJ01-U08
122 Unit 8

8. Handling Exceptions with Exceptions

Case Study
Ms. Koch has invested much time in making her programs more robust against errors.
To report such errors back to the calling program components, she devised many dif-
ferent error codes (e.g., “–1,” in the event that a needed book title was not found in the
database of the online shop). But over time she has lost track of them and, as a result,
error codes have sometimes been misinterpreted or not even recognized as such.

Ms. Koch has therefore explored the built-in Java instruments for exception handling.
From that point on, she decided to use them to catch errors in the program more easily
and reliably. She uses exceptions in specific ways to report exceptions back to the call-
ing program. Now the time-consuming process of defining and interpreting user-
defined error codes is a thing of the past. To define special error situations and provide
them with her own error message, she can program her own exception classes.

8.1 Typical Scenarios of Exception Handling


Exception A number of different exception situations can arise during program execution. For
This is a state in example, a calculation may try to divide by zero, an application that needs to process a
which the program is file may be unable to find the file or there may be an invalid parameter in a method.
unable to continue Such situations can generally be described as states that in some way prevent the pro-
to function normally. gram from continuing normal operation. These situations are, of course, undesirable
and should be prevented using error handling concepts. For example, an invalid user
entry in the online shop should not cause a failure of the entire shop system. This not
only has serious economic ramifications, it would also negatively affect the public per-
ception of the company and customer satisfaction. Instead, the entries should be
ignored and a message should be displayed to the affected user.

In many programming languages that do not have an error handling concept, such
exception situations are mostly identified with specific return values. Here, the return
Error signal values are based on a previously determined definition of possible error signals (e.g.,
This codes an excep- “-1” for “division by zero”). The figure below shows an application for exception han-
tion using a value dling that should be used through the remainder of the unit as a comprehensive exam-
that is outside the ple.
valid value range
(e.g., negative) where
the calling program
must recognize the
coding in order to
respond to the
exception.
Unit 8 123

Handling Exceptions with Exceptions

A customer of the online shop would like to see statistics following their order. For this
purpose, the online shop system invokes different methods of the shopping cart,
including pricePerProduct(). If no problem arises during this program operation, the
information is first returned to the online shop and then is collected and returned to
the customer. But during operation, a number of exception situations can occur. For
example, the shopping cart could be empty due to an error in the database. In such
cases with older programming languages without explicit support for exception han-
dling, error signals are returned. The signals must first be interpreted by the calling
program (here the online shop) and translated into an error message that is readable
by the user (see figure below).
124 Unit 8

However, these approaches have a significant disadvantage because functions, such as


pricePerProduct(), have only one return value and must return technical error signals
and domain return values alike to the calling program through this return value. This
mixture of technical signals and domain values can result in poor software quality and
should be avoided for that reason.

To write more robust programs, there should be a separate channel for signaling errors
that results in the decoupling of domain return values and error signals. A user-defined
data structure for such signals would also have the advantage that it can define differ-
entiated error messages. Finally, it would be desirable to force all calling programs to
catch possible exceptions of a called method. This would ensure that there are solution
strategies in place for frequent error sources.
Unit 8 125

Handling Exceptions with Exceptions

8.2 Standard Exceptions in Java


The Java programming language, with the class Exception, offers an object-oriented Exception
concept for the definition and use of exceptions. Along with a comprehensive collection This class forms the
of predefined standard exceptions (an excerpt is shown in the table below; you can core of object-orien-
find a complete overview on the Programming Guide website), there are also special ted exception han-
language elements for creating (“throwing”) and catching exceptions. dling in Java in
which subclasses
Before describing how to define your own exceptions, it is first necessary to introduce can be used to han-
the use of standard exceptions using the new language elements. Here, we will turn dle many different
once again to the online shop example: Let us assume that the class “ShoppingCart” exception situations.
provides a method that calculates the average price of products purchased and out-
puts it in the console. If the shopping cart is empty, the calculation will try to divide by
zero and this will result in an ArithmeticException. Java offers several alternatives for
handling the exception:

1. The exception is caught within the method.


2. The exception is passed to the calling program.
3. The exception is caught and is then passed to the calling program with a specific
message.

Predefined Standard Exceptions in Java (Excerpt)

Name Description Example

ArithmeticException Division by zero int n = 0;


return 1/n;

ArrayIndexOutOfBound- Access to a list element int[] numbers = new


sException outside the defined area int [8];
(more information on numbers [10] = 4;
this below)

NullPointerException Access to a non-instanti- customer k = null;


ated object c.setLast-
name("Meier");

The figure below shows the first alternative with a code example. It illustrates how the
exception can be detected and handled without the calling program being informed.
The error-prone program section is surrounded by a try block. The catch block can be
used to define which exceptions are occurring in the try block, how those exceptions
should be caught, and how they should be handled. In the example, the result is set to
0 if no product is in the shopping cart.
126 Unit 8

Try/catch block
Exceptions are
caught with a try/
catch block in which
critical program
instructions are con-
tained in the try
block and exceptions
are handled in the
catch block.

Although the code example above shows the use of the new language elements, it does
not yet benefit from all the advantages of the explicit exception handling. More helpful
than simply returning the value 0 is passing the exception to the calling program, espe-
cially if the calling program (here: the online shop) should have responsibility for
exception handling. Thus, in the following, the second alternative for handling excep-
tions in Java is covered: passing exceptions.

For methods to be able to pass exceptions, their signature must be able to be extended
Throws with the keyword throws (see figure below). This is followed by the list of all exceptions
This keyword indi- that appear in the method (here: ArithmeticException). Using the signature, calling pro-
cates in the method grams can recognize which exceptions can be expected by this method. Exception han-
signature which dling by try/catch block must be moved to the calling program. As a result, the example
exceptions can be method pricePerProduct() again becomes significantly more manageable.
thrown by the
method.
Unit 8 127

Handling Exceptions with Exceptions

As the calling program, it is now the task of the online shop to catch and handle the
exceptions. To prevent a possible program abort as shown above, the call of the
method pricePerProduct() is now embedded in a try/catch block. In case of an excep-
tion, the error message is obtained with the method getMessage() of the exception
object and is output in the console. Next, the program can continue with the following
statements.

Tip

Please note that not all of the standard exceptions integrated in Java have to be
handled. For example, if the try/catch block in the above example is left out, this
does not result in a compiler error, even though the signature of the method price-
PerProduct() indicates that it throws an exception. Such exceptions are cal-
led “unchecked” exceptions in the literature.
128 Unit 8

You can recognize them by the fact that they all are subclasses of RuntimeExcep-
tion. This applies, for example, for all the exceptions listed in the table “Predefined
standard exceptions in Java (excerpt).” All other exceptions, i.e., even those you
define yourself, are “checked” exceptions and must be caught.

There is a disadvantage in the code example shown above. For the user of the online
shop, the error message is incomprehensible because it does not identify the cause
(shopping cart is empty), but only the effect (division by zero). Much better, therefore,
would be a context-specific error message that refers to the actual problem. A third
alternative is therefore presented in the following: Passing the exception with the key-
Throw word throw and a specific error message. Here, the exception is again caught in the
This keyword ena- method pricePerProduct() via try/catch block in order to then throw a new Arithmeti-
bles the creation of cException that contains the specific error message. The adapted error message is
an exception. passed as a parameter to the constructor of the exception (see figure below).

In the third version, nothing changes with the calling program, as it must still catch the
declared exception. Only the error message of the exception being handled has
changed.

It should also be noted that several catch blocks can also be defined for a single try
block. This makes sense for example when many different exceptions are possible in
the try block and each of these exceptions has to be handled separately or it is neces-
sary to ensure that, in addition to a particular standard exception, all the other excep-
tions should also be caught.
Unit 8 129

Handling Exceptions with Exceptions

Let us assume that the method pricePerProduct() is much more complex and, in addi-
tion to the ArithmeticException, can also trigger an ArrayIndexOutOfBoundsException
(e.g., because the product list needs to be accessed for recalculating the current prod-
uct sum). In this case, an extended try/catch block might look like the one shown in the
figure below. If an exception occurs in the try block, then the catch blocks are checked
in sequence to determine which one corresponds to the thrown exception. If none of
the special catch blocks match, the exception is caught in the general catch block,
because all the exceptions are in Java subclasses of Exception.

Exception handling with try/catch blocks offers many advantages, but there is also one
situation where the familiar language constructs complicate the program. This happens
whenever a particular program logic has to be invoked every time we execute a try
block, which proves to be a difficult task if we only have the resources thus far acquired
at our disposal. That is why, in addition to the normal processing without exceptions,
there are exactly three other possibilities for exiting the try block. In each of these
cases, it is necessary to ensure that only necessary cleanup tasks are performed. To
130 Unit 8

Finally block avoid such redundant code, you can use the finally block. It is defined following the
This block contains catch blocks and is run each time regardless of whether an exception occurs or not
all statements (see figure below).
regardless of
whether an excep-
tion has occurred in
the try/catch block
or was handled or
not. Here, it is mostly
mandatory cleanup
tasks that are com-
pleted.

8.3 Defining Your Own Exceptions


In the previous unit we saw how more robust programs can be developed using the
language constructs for exception handling that are integrated in Java. The use of try/
catch blocks also allows for separation of domain values and error signals. Yet, until
now the only known option for modifying available mechanisms was throwing a stand-
ard exception with a user-defined error message. In this section, we will look at how to
User-defined excep- program user-defined exceptions to create and catch much more individually tailored
tions exceptions.
You can create pro-
gram-specific excep- In the example in the previous learning cycle, the method pricePerProduct() of the
tions but they must shopping cart was called from the online shop to offer the customer statistics on the
be derived from the last purchase. Division by zero could be neutralized as a possible error source by using
exception class. the ArithmeticException standard exception that is provided for it, but appropriate
standard exceptions do not always exist in Java. An example of this is invoking the
method getMinimumordervalue() in the online shop customer administration. The
method should create an exception if the minimum order value is negative. Because
this is not an exception that can be covered with standard exceptions, a user-defined
exception should be defined for such a case: the MinimumordervalueNegativeException
(see figure below).
Unit 8 131

Handling Exceptions with Exceptions

Each exception, regardless of whether it is the standard exception or a user-defined


exception, must derive from the superclass Exception. The constructors can be used to
define which messages are created by the exception. If the standard constructor is
used for creating it, a standard error message should be defined. For this purpose the
constructor of the superclass (Exception) is invoked with the desired string as parame-
ter. It interprets the past parameter as an error message and supplies it to the calling
program via the method getMessage(). If you want to create the exception with an error
message that is not known until runtime, you can add another constructor with a
parameter that passes the error message that is sent immediately to the constructor of
the superclass.
132 Unit 8

The method getMinimumordervalue() can now be thrown instead of the error signal
MinimumordervalueNegativeException (see figure above). In the example, the exception
was created with the standard error message. But just as with the standard exceptions,
you could also pass a special error message as a parameter here. Now, the return value
no longer has to be searched for an error signal in the calling program (see figure
below), of the method getCustomerdata(). Instead, the call of getMinimumordervalue()
is simply embedded in a try/catch block. In the event of an exception, the related error
message is output in the console.
Unit 8 133

Handling Exceptions with Exceptions

Summary

With its many exception handling language constructs, Java offers a useful tool for
programming applications. The use of a separate channel for signaling exceptions
ensures that return values contain only correct domain data and is free of error
codes. Complicated conditional queries for interpretation of these codes and their
handling now are no longer needed and can be replaced with simply structured
try/catch blocks.

Built-in Java standard exceptions offer the option to catch frequently encountered
error situations, e.g., division by zero or access to a non-initialized object. If these
are not sufficient, Java allows you to derive standard exceptions using specially
defined exception subclasses with specific error messages.
134 Unit 8

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
Unit 9
Programming Interfaces with Interfaces

STUDY GOALS

On completion of this unit, you will have learned …

… what interfaces are and what situations they are used in.

… what special characteristics interfaces have in contrast to classes.

… under which rules interfaces are defined.

DL-E-DLBCSOOPJ01-U09
136 Unit 9

9. Programming Interfaces with Interfaces

Case Study
During the development of the online shop, Ms. Koch presented prototypes represent-
ing the current status of development to the client at regular intervals. During this time,
the client never actually had to commit to a specific technology for storing the cus-
tomer data. Ms. Koch therefore constantly had to interchange the program components
of the online shop. Because she found this very irritating, she looked for a solution to
solve this problem. Then she discovered the concept of interfaces and decided to
adapt the language constructs of Java to define and use interfaces.

Now, Ms. Koch can use interfaces in Java so that she can implement interchangeable
solutions for storing customer data in the online shop. Now, by means of interfaces,
she also has a way to resolve the problem of the multiple inheritance, which is not
supported in Java, and use it to specify software components that are visible to the
outside.

9.1 Typical Scenarios of Programming Interfaces


Gang of four The “gang of four” were already heralding the use of interfaces in 1995. It was better to
A group of four program against an interface than against an implementation, was their claim (see
authors who have Gamma et al., 1995). There are many scenarios where this concept makes sense. Indeed,
written frequently it ensures a clear separation of the specification and the implementation. This means
cited literature on that it is possible to neatly separate the process of defining what specific classes or
the subject of soft- entire packages should be able to do (specification) and how this functionality is to be
ware technology. implemented technically (implementation).

Implementation This separation has two advantages: First, it allows for a more flexible software archi-
This is the technical tecture, as the implementation can be interchanged if necessary without significant
implementation adaptation. An example is the print function in text processing: The interface for a print
(programming) of a driver is clearly defined and is known for all printer driver producers. A user can install
predetermined func- any drivers and then select the appropriate printer as needed—be it a PDF printer or
tionality. The func- an actual printer (see figure below).
tionality can be
determined by an
interface, among
other things.
Unit 9 137

Programming Interfaces with Interfaces

The second advantage of the separation of specification and implementation is that it


increases the usability of classes or packages. A class that offers (implements) a partic-
ular interface can be used anywhere such a functionality is needed. The program in
which the class is integrated does not have to be adapted. In the example of the
printer drivers, this means that a producer does not have to program a separate printer
driver for each PC, laptop, or model-specific features, etc. Whenever the interface
remains the same—and this is always the case for a specific version of an operating
system—a driver can be used for all PCs on which this operating system version is
installed (see figure below).

Tip

With the introduction of interfaces, an additional instrument is available for utili-


zing the concept of polymorphism. You have already seen polymorphism at work in
the example of inheritance. There, it was shown how the method of a superclass
138 Unit 9

was re-implemented in a different way by subclasses. If all the classes from an


inheritance hierarchy are saved in a shared list and the method of the superclass is
invoked, the most suitable implementation will be selected by the runtime environ-
ment (dynamic binding). Using interfaces, the restriction can be removed so that
such classes have to be located in a common inheritance hierarchy. The critical
thing then is simply that they implement a common interface. Interfaces are thus
suitable as an even more powerful instrument for polymorphism.

The function of interfaces can also be seen in the example of the online shop: Assume
that the customer administration requires a flexibly interchangeable component for
long-term storage of customer data. The data should be saved in a file or in a database
according to requirements. With the previously available methods, you would program
any alternative as a user-defined class and then use it in the customer administration
(see figure below). Here, it is critical that both components always offer the same
methods with the same parameters. If this is not the case for an alternative, then
extensive adaptations to the program code in the customer administration would be
necessary in case of any changes.

Coming up, we will see how the program can be solved more elegantly and efficiently
using interfaces.
Unit 9 139

Programming Interfaces with Interfaces

9.2 Interfaces as Programming Interfaces in Java


Interfaces are defined in Java with the keyword interface. The syntax is very reminiscent Interface
of a class, but with the difference that all the methods are abstract. This means that A number of meth-
the methods consist only of the signature and thus have no body within curly brackets ods that can be
(see figure below). In this way, you can specify what an implementing class has to be implemented by
able to do without anticipating the “how.” In defining the interfaces, please note that classes. While meth-
they must be stateless. Therefore, aside from constants, attributes cannot be defined. ods are only realized
in classes, in interfa-
ces there can only
be methods without
a body.

Using the keyword implements, a class can show which interface(s) it realizes. It
thereby commits to offer an implementation of this/these interface(s) for each method.

In UML the notation of interfaces also resembles that of classes. To differentiate them,
the stereotype <<interface>> is used (see figure below). A use association, represented Use association
by a dotted arrow with open head and the stereotype <<use>>, can be used to indicate This association
that a class is using an interface. This means the class invokes at least one method of indicates that a class
the interface. uses an interface.
140 Unit 9

The implementing class, like the inheritance notation, points to the interface with a
closed arrowhead. But unlike inheritance, the arrow is dotted.

With these options for modeling and programing interfaces, the problem of flexibility
for interchangeable customer storage can be resolved. Before examining the Java code
in detail, we will look at how the roles are divided between the classes using a class
diagram. An interface (e.g., ICustomerStorage) is now inserted between the customer
administration and the individual alternatives for long-term storage of customer data.
The interface defines a series of methods that are necessary independent of the imple-
mentation for long-term storage of customer data. The customer administration uses
this interface in one of its methods, e.g., in the figure above, where it plays the role of
the class used. The alternatives for interface implementation (FileCustomerStorage and
DBCustomerStorage) play the role of the classes to be implemented. They offer a reali-
zation for each method that was agreed in the interface ICustomerStorage.
Unit 9 141

Programming Interfaces with Interfaces

Accompanying Java code for the class diagram is found in the figure below. It shows the
use of the interface in an example method, the definition of the interface and an exam-
ple implementation. (For reasons of space, the instructions in the body of the imple-
mented methods are excluded.)
142 Unit 9

Because the methods required for storing customer data are now defined in an inter-
face, they can be interchanged as often as desired without considerable time and effort
(flexibility). Conversely, the implementation for the storage of customer data can be
used in principle everywhere else in the program where such an interface is needed
(reusability).

We conclude with additional information on interfaces in Java. Among these is the fact
that interfaces can also inherit from other interfaces. In this way common features of
interfaces can be combined and extended depending on the application with minimal
Unit 9 143

Programming Interfaces with Interfaces

additional maintenance. With regard to interfaces, Java also supports the concept of
multiple inheritances. This means that, unlike classes, interfaces can even inherit from
more than one interface. However, the same keyword extends is used (see figure
below).
144 Unit 9

The attentive reader will also have noticed that the definition of interfaces is very simi-
lar to abstract classes. There are, in fact, several parallels: Abstract classes can also
define cross-class functionalities using abstract methods. Unlike abstract classes, how-
ever, the inheritance hierarchy plays a role in interfaces. That is, even “unrelated”
classes can be assigned to an identical interface and a class can implement more than
one interface. In addition, unlike abstract classes, with interfaces, the mixing of imple-
mented and abstract methods is prohibited. The prohibition against defining attributes
likewise prevents the programming of state-specific interfaces.

Summary

The use of interfaces ensures a clear separation of the specification and the imple-
mentation. It is thus possible to separately determine which functions specific
classes should offer and how this functionality should be implemented technically.
There are two resulting advantages: On the one hand, it allows for a more flexible
software architecture, as the implementation of an interface can be interchanged if
necessary without significant adaptation for the classes used. On the other hand, it
increases the reusability of classes. This is because an interface implementation
can be used wherever the functionality of the interface is needed.

Knowledge Check

Did you understand this unit?

You can check your understanding by completing the questions for this unit on the
learning platform.

Good luck!
Evaluation 145

Congratulations!

You have now completed the course. After you have completed the knowledge tests on
the learning platform, please carry out the evaluation for this course. You will then be
eligible to complete your final assessment. Good luck!
Appendix 1
List of References
148 Appendix 1

List of References

Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1995). Design patterns: Elements of reus-
able object-oriented software. Addison-Wesley.

Krüger, G., & Stark, T. (2011). Handbuch der Java-Programmierung [Handbook for Java
programming.] (7th ed.). Addison-Wesley. http://www.javabuch.de

Lahres, B., & Raýman, G. (2006). Praxisbuch Objektorientierung. [Object orientation prac-
tice book.] Rheinwerk. http://openbook.rheinwerk-verlag.de/oo/

Oestereich, B. (2012). Analyse und Design mit der UML 2.5: Objektorientierte Softwareent-
wicklung. [Analysis and design with UML 2.5: Object-oriented software development.]
Oldenbourg.

Oracle. (2013a). The Java tutorials. http://docs.oracle.com/javase/tutorial/

Oracle. (2013b). Java platform standard edition 7.0 API specification. http://
docs.oracle.com/javase/7/docs/api/index.html

Oracle. (2013c). Code conventions for the Java programming language. http://
www.oracle.com/technetwork/java/codeconventions-150003.pdf

Oracle (2013d). How to write doc comments for the Javadoc tool. http://
www.oracle.com/technetwork/java/javase/documentation/index-137868.html

ProgrammingGuide. (n.d.). List of Java exceptions. https://programming.guide/java/list-


of-java-exceptions.html

Ratz, D., Schefer, J., & Seese, D. (2011). Grundkurs Programmieren in Java 6. [Basic course
in Java programming 6.] Hanser.

Reviewland. (2017). Kaffeemaschinen Vergleich—Die besten Filterkaffeemaschinen 2017.


[Coffee machine comparison—The best filter coffee machines 2017.] https://review-
land.website/2017/07/25/kaffeemaschinen-vergleich-die-besten-filterkaffeemaschi-
nen-2017/

Ullenboom, U. (2011). Java ist auch eine Insel [Java is also an island.] (10th ed.). Rhein-
werk. http://openbook.rheinwerk-verlag.de/javainsel/
Appendix 2
List of Tables and Figures
150 Appendix 2

List of Tables and Figures

Overview of the Historical Development of Programming Concepts


Source: Brückmann & Dreikauss, 2020.

Drawing of a Clock
Source: Brückmann & Dreikauss, 2020.

Example Scenario of a Simple Coffee Machine


Source: Brückmann & Dreikauss, based on Reviewland, 2017.

Interaction Between Objects in a Coffee Machine


Source: Brückmann & Dreikauss, 2020.

Advanced Coffee Machine


Source: Brückmann & Dreikauss, 2020.

Objects of a Coffee Machine


Source: Brückmann & Dreikauss, 2020.

Identified Classes
Source: Brückmann & Dreikauss, 2020.

Attributes of the “Customer” Class


Source: Brückmann & Dreikauss, 2020.

Properties of Attributes
Source: Brückmann & Dreikauss, 2020.

Identified Attributes of the Classes


Source: Brückmann & Dreikauss, 2020.

Properties of Methods
Source: Brückmann & Dreikauss, 2020.

Attributes and Methods of the “Customer” Class


Source: Brückmann & Dreikauss, 2020.
Appendix 2 151

List of Tables and Figures

Typical Associations between Classes


Source: Brückmann & Dreikauss, 2020.

Representing Relationships
Source: Brückmann & Dreikauss, 2020.

Multiplicities in Relationships
Source: Brückmann & Dreikauss, 2020.

Example Scenario with Additional Associations


Source: Brückmann & Dreikauss, 2020.

Overview of UML Design Types


Source: Brückmann & Dreikauss, 2020.

Objects and Classes


Source: Brückmann & Dreikauss, 2020.

Development with the C Programming Language


Source: Brückmann & Dreikauss, 2020.

Development with the Java Programming Language


Source: Brückmann & Dreikauss, 2020.

Structure of the “Customer” Class


Source: Brückmann & Dreikauss, 2020.

Basic Elements of a Class in Java


Source: Brückmann & Dreikauss, 2020.

“Customer” Class with Attributes Added


Source: Brückmann & Dreikauss, 2020.

Basic Elements of an Attribute in Java


Source: Brückmann & Dreikauss, 2020.
152 Appendix 2

Methods of the “Customer” Class


Source: Brückmann & Dreikauss, 2020.

Basic Elements of a Method in Java


Source: Brückmann & Dreikauss, 2020.

Getter and Setter Methods for the “Customer” Class


Source: Brückmann & Dreikauss, 2020.

Implementation of Getter and Setter Methods for the Attribute of the “Customer”
Class
Source: Brückmann & Dreikauss, 2020.

Main Method as the Starting Point of a Class


Source: Brückmann & Dreikauss, 2020.

Main Method in a Class Diagram


Source: Brückmann & Dreikauss, 2020.

Example on How to Implement a Main Method


Source: Brückmann & Dreikauss, 2020.

Primitive Data Types in Java


Source: Brückmann & Dreikauss, 2020.

String as Data Type for Strings


Source: Brückmann & Dreikauss, 2020.

Declaration and Assignment of Variables


Source: Brückmann & Dreikauss, 2020.

Summary of Declaration and Assignment


Source: Brückmann & Dreikauss, 2020.

Important Arithmetic Operators


Source: Brückmann & Dreikauss, 2020.
Appendix 2 153

List of Tables and Figures

Important Logical Operators


Source: Brückmann & Dreikauss, 2020.

Important Relational Operators


Source: Brückmann & Dreikauss, 2020.

Example of the Comparison of Primitive Data Types


Source: Brückmann & Dreikauss, 2020.

Example of the Comparison of Reference Data Types


Source: Brückmann & Dreikauss, 2020.

Equality of Reference Data Types


Source: Brückmann & Dreikauss, 2020.

Concatenation of Strings
Source: Brückmann & Dreikauss, 2020.

Class Diagram with the “Shopping Cart” and “Customer” Classes


Source: Brückmann & Dreikauss, 2020.

Use Case for Conditional Branches


Source: Brückmann & Dreikauss, 2020.

Example of Simple Conditional Branches


Source: Brückmann & Dreikauss, 2020.

Use Case for Nested Branches


Source: Brückmann & Dreikauss, 2020.

Example of Nested Branches


Source: Brückmann & Dreikauss, 2020.

Example for if-else if-else Branches


Source: Brückmann & Dreikauss, 2020.
154 Appendix 2

Example of a while Loop


Source: Brückmann & Dreikauss, 2020.

Example of a do-while Loop


Source: Brückmann & Dreikauss, 2020.

Example of a for Loop


Source: Brückmann & Dreikauss, 2020.

Example for Nested Control Structures


Source: Brückmann & Dreikauss, 2020.

Packages of the Online Shop


Source: Brückmann & Dreikauss, 2020.

Declaration of the Package of a Class


Source: Brückmann & Dreikauss, 2020.

Visibility Modifiers
Source: Brückmann & Dreikauss, 2020.

Implemented Classes
Source: Brückmann & Dreikauss, 2020.

Example Scenario Completed by Relations


Source: Brückmann & Dreikauss, 2020.

Equal Attributes are Combined in the Superclass


Source: Brückmann & Dreikauss, 2020.

Different Pages for Different Kinds of Products


Source: Brückmann & Dreikauss, 2020.

Transitive Properties of Inheritance


Source: Brückmann & Dreikauss, 2020.
Appendix 2 155

List of Tables and Figures

Inheritance of Associations
Source: Brückmann & Dreikauss, 2020.

Inheritance in Java with extends in the Class Declaration


Source: Brückmann & Dreikauss, 2020.

Declaration of the “Book” Class for the “Product” Class


Source: Brückmann & Dreikauss, 2020.

Invoking Inherited Methods


Source: Brückmann & Dreikauss, 2020.

Assignment Compatibility
Source: Brückmann & Dreikauss, 2020.

Availability of Attributes and Methods Dependent on the Type of the Variable


Source: Brückmann & Dreikauss, 2020.

Generic Loop for All Products, Which Generates a List of Manufacturers


Source: Brückmann & Dreikauss, 2020.

Overriding an Inherited Method


Source: Brückmann & Dreikauss, 2020.

Invoking an Overridden Method


Source: Brückmann & Dreikauss, 2020.

Super Addresses the Superclass


Source: Brückmann & Dreikauss, 2020.

Access to Implementation in the Superclass with super


Source: Brückmann & Dreikauss, 2020.

The “Product” Superclass and Its Subclass


Source: Brückmann & Dreikauss, 2020.
156 Appendix 2

Designation of the “Product” Class as Abstract Class, Two Variations


Source: Brückmann & Dreikauss, 2020.

Designation of an Abstract Class in Java


Source: Brückmann & Dreikauss, 2020.

Designation of an Abstract Method


Source: Brückmann & Dreikauss, 2020.

Implementation of an Abstract Method by Overridding


Source: Brückmann & Dreikauss, 2020.

Declaration of Variables of the Type Abstract Class


Source: Brückmann & Dreikauss, 2020.

The Different Kinds of Products in the Class History


Source: Brückmann & Dreikauss, 2020.

Choice of Implementation at Runtime


Source: Brückmann & Dreikauss, 2020.

Application of the instanceof Operator to Test for Class Members


Source: Brückmann & Dreikauss, 2020.

Declaration and Application of a Static Attribute


Source: Brückmann & Dreikauss, 2020.

Declaration and Application of Static Methods


Source: Brückmann & Dreikauss, 2020.

Static Attributes and Methods of the “Math” Class


Source: Brückmann & Dreikauss, 2020.

Utilization of the New Operator in the Main Method of an Auto Management


Source: Brückmann & Dreikauss, 2020.
Appendix 2 157

List of Tables and Figures

Definition and Invocation of the Standard Constructor


Source: Brückmann & Dreikauss, 2020.

Online Form to Create a New Customer Account (Left); Possible Implementation


(Right)
Source: Brückmann & Dreikauss, 2020.

Common Allocation of the Object Attributes by Setter Methods


Source: Brückmann & Dreikauss, 2020.

Example of an Overloaded Standard Constructor


Source: Brückmann & Dreikauss, 2020.

Utilization of an Overloaded Constructor as an Alternative to the Application of


Many Setter Methods
Source: Brückmann & Dreikauss, 2020.

Second, Right Input Mask (Left), Possible Implementation (Right)


Source: Brückmann & Dreikauss, 2020.

Defining a Chain of Overloaded Constructors


Source: Brückmann & Dreikauss, 2020.

Copy Constructor, Which Can Create a Copy of a Customer Object


Source: Brückmann & Dreikauss, 2020.

Extended UML Class Diagram of the Online Shop Example


Source: Brückmann & Dreikauss, 2020.

Invocation of a Constructor of the Superclass with super ()


Source: Brückmann & Dreikauss, 2020.

Example Scenario for the Exception Handling of Error Signals


Source: Brückmann & Dreikauss, 2020.

Handling Error Situations with Signals


Source: Brückmann & Dreikauss, 2020.
158 Appendix 2

Predefined Standard Exceptions in Java (Excerpt)


Source: Brückmann & Dreikauss, based on ProgrammingGuide, 2020.

Catching Standard Exceptions with try/catch Block


Source: Brückmann & Dreikauss, 2020.

Second Version: Catching of a Passed Exception


Source: Brückmann & Dreikauss, 2020.

Third Version: Passing the Exception with Adapated Error Message


Source: Brückmann & Dreikauss, 2020.

Extended try/catch Block


Source: Brückmann & Dreikauss, 2020.

Use of the finally Blocks


Source: Brückmann & Dreikauss, 2020.

Definition of User-Defined Exception


Source: Brückmann & Dreikauss, 2020.

Throwing a User-Defined Exception


Source: Brückmann & Dreikauss, 2020.

Catching a User-Defined Exception


Source: Brückmann & Dreikauss, 2020.

Alternative Printer Driver as Example for Flexible Software Architecture


Source: Brückmann & Dreikauss, 2020.

Reuse by Common Interfaces


Source: Brückmann & Dreikauss, 2020.

Example Scenario for the Use of Interfaces: the Changeable Customer Storage
Source: Brückmann & Dreikauss, 2020.
Appendix 2 159

List of Tables and Figures

Definition and Implementation of an Interface in Java


Source: Brückmann & Dreikauss, 2020.

Notation of Interfaces in UML


Source: Brückmann & Dreikauss, 2020.

Class Diagram for the Use of Interfaces in the Online Shop


Source: Brückmann & Dreikauss, 2020.

Application, Definition, and Implementation of an Interface in the Online Shop


Source: Brückmann & Dreikauss, 2020.

Inheritance of Interfaces Shown by the Example of a Printer Combination Device


Source: Brückmann & Dreikauss, 2020.
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

You might also like