Professional Documents
Culture Documents
Dlbcsoopj01 Course Book
Dlbcsoopj01 Course Book
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
Module Director
Prof. Dr. Damir Ismailović
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
Unit 2
Introduction to Object-Oriented Modeling 22
2.1 Structuring Problems With Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Unit 3
Programming Classes in Java 38
3.1 Introduction to the Java Programming Language . . . . . . . . . . . . . . . . . . . . 38
Unit 4
Java Language Constructs 58
4.1 Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Unit 5
Inheritance 82
5.1 Modeling and Inheritance in the Class Diagram . . . . . . . . . . . . . . . . . . . . . 83
Unit 6
Important Object-Oriented Concepts 98
6.1 Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Unit 7
Constructors for Generating Objects 110
7.1 The Standard Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Unit 8
Handling Exceptions with Exceptions 122
8.1 Typical Scenarios of Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Unit 9
Programming Interfaces with Interfaces 136
9.1 Typical Scenarios of Programming Interfaces . . . . . . . . . . . . . . . . . . . . . . 136
Appendix 1
List of References 148
Appendix 2
List of Tables and Figures 150
Introduction
Object-Oriented Programming With Java
8 Introduction
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
DL-E-DLBCSOOPJ01-U01
12 Unit 1
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.
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.”
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.
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
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
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 Responsibilities/function
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
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
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
DL-E-DLBCSOOPJ01-U02
22 Unit 2
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.
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
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.
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.
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
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
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
Properties of Methods
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.
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
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.
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
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
Knowledge Check
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
… which basic elements a Java class consists of and how to program them in Java.
DL-E-DLBCSOOPJ01-U03
38 Unit 3
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.
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
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
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:
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.
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.
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.
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.
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
Code example 2
Here, both the parameter lists and the signatures are different:
Code example 3
Here, only the return data types are different, but not the method names or the
parameter lists. The signatures are identical:
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
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
Here, the getter method of the attribute lastname is invoked to store the value of
lastname in a local variable id1.
Code example 2
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
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
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.”
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.
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:
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.
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 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
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
… what primitive data types Java has and what value range they cover.
… 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
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.
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.
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
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
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
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
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
Operation Operator
Can Example
be
used
with
data
types
Operation Operator
Can Example
be
used
with
data
types
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
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
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
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
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
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 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
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
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
You can check your understanding by completing the questions for this unit on the
learning platform.
Good luck!
Unit 5
Inheritance
STUDY GOALS
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
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.
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
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
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
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
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
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
… how to use abstract classes to set limits on which classes instances can be generated
from.
… 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
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.
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
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.”
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.”
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
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
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.
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
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.
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
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
… how to use different constructors to create objects with specially tailored defaults.
DL-E-DLBCSOOPJ01-U07
110 Unit 7
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.
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
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.
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
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.
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
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.
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.
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
Summary
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
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
… what means Java has at its disposal for catching, throwing, or handling exceptions.
… how you can program your own exceptions to cover such cases.
DL-E-DLBCSOOPJ01-U08
122 Unit 8
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.
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
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
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
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
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
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.
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
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
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
… what interfaces are and what situations they are used in.
DL-E-DLBCSOOPJ01-U09
136 Unit 9
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.
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
Tip
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
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
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
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
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. (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
Ratz, D., Schefer, J., & Seese, D. (2011). Grundkurs Programmieren in Java 6. [Basic course
in Java programming 6.] Hanser.
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
Drawing of a Clock
Source: Brückmann & Dreikauss, 2020.
Identified Classes
Source: Brückmann & Dreikauss, 2020.
Properties of Attributes
Source: Brückmann & Dreikauss, 2020.
Properties of Methods
Source: Brückmann & Dreikauss, 2020.
Representing Relationships
Source: Brückmann & Dreikauss, 2020.
Multiplicities in Relationships
Source: Brückmann & Dreikauss, 2020.
Implementation of Getter and Setter Methods for the Attribute of the “Customer”
Class
Source: Brückmann & Dreikauss, 2020.
Concatenation of Strings
Source: Brückmann & Dreikauss, 2020.
Visibility Modifiers
Source: Brückmann & Dreikauss, 2020.
Implemented Classes
Source: Brückmann & Dreikauss, 2020.
Inheritance of Associations
Source: Brückmann & Dreikauss, 2020.
Assignment Compatibility
Source: Brückmann & Dreikauss, 2020.
Example Scenario for the Use of Interfaces: the Changeable Customer Storage
Source: Brückmann & Dreikauss, 2020.
Appendix 2 159
Mailing address:
Albert-Proeller-Straße 15-19
D-86675 Buchdorf