0% found this document useful (0 votes)
16 views123 pages

Introduction to Object-Oriented Programming

This document provides an introduction to object-oriented programming (OOP) with a focus on its principles, phases, and the concept of objects. It outlines the software development process, which includes object-oriented analysis, design, and programming, emphasizing the importance of understanding system requirements and object interactions. The document also highlights the benefits of using object orientation for managing complexity in software systems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views123 pages

Introduction to Object-Oriented Programming

This document provides an introduction to object-oriented programming (OOP) with a focus on its principles, phases, and the concept of objects. It outlines the software development process, which includes object-oriented analysis, design, and programming, emphasizing the importance of understanding system requirements and object interactions. The document also highlights the benefits of using object orientation for managing complexity in software systems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT-ORIENTED

PROGRAMMING WITH JAVA


DLBCSOOPJ01
UNIT 1
INTRODUCTION TO OBJECT-ORIENTED
SYSTEM DEVELOPMENT

STUDY GOALS

On completion of this unit, you will have learned …

– what is meant by the term object orientation.


– what objects are and what they consist of.
– which phases make up the software development process.
– the basic principles of object-oriented software development.
1. INTRODUCTION TO OBJECT-ORIENTED
SYSTEM DEVELOPMENT

Case Study
As a developer, Ms. Koch is supposed to program an online shop for the sale of media of all
types (books, music, films, and games). The customer, Mr. Lange, explains to her which
products should be sold and what special offers he has planned. It is now time to begin
development and Ms. Koch is considering how best to approach this task.

1.1 Object Orientation as a Way of


Looking at Complex Systems
Object orientation The term object orientation (abbreviated as OO) refers to an approach in software tech-
An approach that sup- nology that was developed primarily to support the development, enhancement, and
ports the creation,
enhancement, and main- maintenance of complex enterprise IT systems. Here object orientation is a view of com-
tenance of complex enter- plex systems that conceives these systems as an interaction of abstract or real entities—
prise IT systems. Here, the the objects themselves.
IT system is described as
the interaction of com-
plex objects. “Object orientation” therefore is not a programming language or a modeling language. It
is not an operating system, program or application, nor is it a process model, develop-
ment method or environment or database. But there are languages, methods and databa-
ses that support the object-oriented approach in particular ways.

The widespread acceptance of object orientation in industrial applications began in the


early 1990s. A key factor here was the very high cost of service and advanced development
of large IT systems, among other factors. Typically, enterprise applications are being
developed on an ongoing basis and adapted to meet business and technical trends. Thus,
as the functional scope of IT systems grows, so too does the number of lines of program
code (LOC). Often enterprise information systems contain several millions of lines of pro-
gram code that have been written jointly by several hundred developers.

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


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

14
Table 1: Overview of the Historical Development of Programming Concepts

Programming concept Typical elements Areas of application

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


ble expression values longer in use today

Assembly code movb $0x61; processor com- Controllers for electrotechnical


mands and direct address of devices (fans, motors, air-condi-
technical memory addresses tioners), reactive systems (sen-
sor systems), embedded pro-
gramming

Imperative programming WHILE, FOR, GOTO; an advance Small programs to solve simple
on assembly code, allow loops tasks, usually in special pro-
and targeted jumps gramming languages

Structured programming Procedures; structuring a pro- Simple Web applications, tech-


gram in procedures (functions) nical control components
and subprocedures (subfunc-
tions)

Object-oriented programming Classes, objects, associations; a Large and complex industrial


program consists of cooperating software systems
objects

Component-based development Components, interfaces; parts of Reuse of previously program-


a system are combined in a com- med functions; the individual
ponent that performs very spe- components are usually pro-
cific tasks grammed with object-oriented
programming

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


program code is generated auto- of cross-cutting functions (e.g.,
matically from software models login mechanisms), the gener-
using code generators ated program code can reflect
the concepts of object orienta-
tion

Source: Brückmann & Dreikauss, 2020.

1.2 The Object as a Basic Concept of


Object Orientation
The concept object is present in the very name “object orientation” and refers to a part of Object
a system. For object-oriented programming, this means that an object is a part of a pro- This is a part of a software
system. At the time of
gram and also that a program developed with object-oriented programming will consist execution, object-orien-
almost exclusively of objects. An object can then contain attributes and methods itself. ted systems take the form
You can use attributes (also: properties) to store information (e.g., current values of varia- of objects in the main
memory of a computer.
bles) in an object. The attributes of an object are hidden from direct access from other
Attributes
objects and thus protected. This means that the values currently saved in an object cannot Elements of objects that
be changed by other objects (principle of data encapsulation). are used for saving con-
crete values are called
attributes.

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

Figure 1: Drawing of a Clock

Source: Brückmann & Dreikauss, 2020.

1.3 Phases in the Object-Oriented


Development Process
Before beginning the actual programming of complex IT systems, all developers must
understand exactly

• what specifically the system should do,


• what information has to be saved in the system, and
• who is going to use the system later and for what purpose.

In addition, the rough structure of the system must be defined by the system architect in
the form of a system architecture.

Thus, before Ms. Koch can actually begin programming the online shop, she must analyze
the problem or task and consider which objects the system should consist of. Only then
can she begin actual goal-directed programming. The process of going through these dif-

16
ferent phases is called the software development process (also: SW process). The goal of Software development
a SW development process is to develop a functional system that meets the requirements process
This process consists of
of the clients with respect to functionality, quality, and development costs. activities in which the
goal is the development,
An object-oriented development process consists of three different phases: enhancement, or servic-
ing of software. This proc-
ess is divided into several
• Object-oriented analysis (OOA) phases.
• Object-oriented design (OOD)
• Object-oriented programming (OOP)

The object-oriented analysis determines what a system should do. The goal of the analysis
is to gain a comprehensive understanding of the functional relationships within the sys-
tem being built. Here, objects in the real world are replicated in a functional model and
only the properties (attributes) that are relevant to the system are included. This analysis
model acts first as a means of communication between the developers and the client
and/or the users of the system. It is also the starting point for the next phase: the object-
oriented design.

The object-oriented design forms a bridge between the analysis and implementation. Object-oriented design
Here, the design of the system is completed using the analysis model as a basis: The func- This is a phase in the
object-oriented SW proc-
tional analysis model is extended by adding technical information so that a programmer ess. Its goal is the techni-
can implement the program code based on the design. In this step, you define which types cal design of the system,
of objects are needed, which attributes and methods they will have and which objects will building on the analysis
model. The result is the
cooperate with each other and in what manner. For complex systems, this task can only be design of the system.
completed by experienced system architects. The quality of the design is generally crucial
for the quality of the programmed system and any future work to extend or customize the
system.

In object-oriented programming a system design is translated into functioning program Object-oriented


code. The developer programs the program code following the specifications defined dur- programming
This is a phase in the
ing the design. The analysis and design are necessary preliminary tasks, but the actual IT object-oriented SW proc-
system is developed exclusively from the implemented program code. That is, if the pro- ess. The goal is the devel-
grammers fail to adhere to the specifications, there is a risk that design decisions will not opment of functional pro-
gram code using the
be implemented appropriately and the system will ultimately behave differently than was design as a basis. The
intended. Furthermore, errors during analysis and design can be propagated in the pro- result is the finished pro-
gram.
gram code if the developer fails to recognize them early.

Example

For Ms. Koch, this means that, in implementing her online shop, she will first have to
exhaustively examine Mr. Lange's wishes and expectations. In this way, she is able to arrive
at an understanding of what business activities are relevant for an online shop and how
exactly the individual processes (e.g., product ordering, payment processing, collections)
will operate.

Next, she must consider the technical design of the online shop. This does not, however,
refer to the visual appearance of the user interface, but to the question of which (techni-
cal) objects the online shop should consist of and how these should cooperate. In addi-

17
tion, Ms. Koch must decide which technologies should be utilized: She can either select
and adapt an existing shop system or program a new one. Also relevant is the question of
which database will be considered and which programming language she would like to
use in programming the online shop.

1.4 Basic Principle of Object-Oriented


System Development
As previously discussed, object orientation is a way of looking at complex systems as an
interaction of cooperating objects. Any system can in theory also be planned and built
without object orientation. But the experience of the past 20 years of software engineering
has shown that with the consistent application of object orientation there are fewer prob-
lems in the scaling, stability, and extensibility of IT systems. Object orientation in software
development can therefore be understood as a principle and a means of managing the
complexity of software systems.

Especially the quality goals of simple extensibility, better testability, and better maintaina-
bility can be achieved relatively easily with object-oriented concepts.

Example

Without exploring the theoretical background, the following example scenario of a simple
coffee machine shows how object orientation affects the viewing of technical systems.

18
Figure 2: Example Scenario of a Simple Coffee Machine

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

In the figure above, a schematic cross-sectional view of a coffee machine is shown. Trans-
lated into the terms of object orientation, the coffee machine can be considered an “inter-
action of cooperating objects,” as shown in the figure below. The water tank object is con-
nected to the water pipe object. The water pipe includes a non-return valve object and is
connected to the filter object. The heating element object heats the water pipe and the
hot plate object. The hot plate keeps the coffee pot object warm. The coffee pot fills up
through the filter object.

19
Figure 3: Interaction between Objects in a Coffee Machine

Source: Brückmann & Dreikauss, 2020.

A little later Mr. Lange decides that he would like to control the coffee machine with a
clock, and instead of the water tank would rather have a direct connection to the drinking
water network. The figure below now shows an extended coffee machine as understood in
the terms of object orientation: The water tank has been replaced with the drinking water
supply. Now the water pipe no longer cooperates with the tank, but instead with the drink-
ing water supply (shown by the connecting line between drinking water supply and water
pipe). A clock object has also been associated with the heating element. Through this con-
nection, the function of “heating” the heating element can be controlled with the clock,
but all other existing internal relationships within the coffee machine remain unchanged.

Figure 4: Advanced Coffee Machine

Source: Brückmann & Dreikauss, 2020.

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

Table 2: Objects of a Coffee Machine

Objects Responsibilities/function

Water tank, later replaced by drinking water sup- Water supply


ply

Water pipe Transport water

Non-return valve Control the water flow direction

Heating element Convert electrical energy into heat

Hot plate Heat coffee pot

Filter Hold coffee grains and allow water to flow through

Clock Trigger signal when configured time is reached

Source: Brückmann & Dreikauss, 2020.

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

SUMMARY
Object orientation is an approach to complex systems in which the sys-
tem is described as the interaction of cooperating objects.

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


replicated with objects in the “digital” world. Only the values and func-
tions that are relevant to the purpose of the system are considered. The
digitally replicated objects save values in their attributes and can calcu-
late values in their methods. Object-oriented programs consist of coop-
erating “digital” objects. The cooperation of objects is realized through
the mutual calling of methods.

21
UNIT 2
INTRODUCTION TO OBJECT-ORIENTED
MODELING

STUDY GOALS

On completion of this unit, you will have learned …

– how the concepts object and class fit together.


– how classes are identified.
– how attributes of classes are described.
– how methods of classes are described.
– how associations between classes are described.
– what the Unified Modeling Language (UML) is.
2. INTRODUCTION TO OBJECT-ORIENTED
MODELING

Case Study
Now that Ms. Koch is certain that her project is going to last several weeks, she has deci-
ded to use an object-oriented approach in analyzing the online shop for Mr. Lange. To this
end, she would like to document all the objects that are needed, identify their attributes
and methods, and document them in the appropriate form. Though she has a rough idea
of how she can represent the online shop and the products, she also wants to be sure that
she understands and has thought everything through before programming. Here, Ms.
Koch needs to know how to identify objects and what methods to use, both in represent-
ing the elements of objects (i.e., attributes and methods) and the cooperation between
objects.

2.1 Structuring Problems With Classes


We have learned about the object as a basic concept in object orientation. An object is a
self-contained entity that is capable of action, for example the auto “E-CL 2343,” the lamp
“Kyist,” the customer “Mr. Meier,” or the contract “P-DFD-23.” In object-oriented develop-
ment, objects in the physical (real) world are replicated as objects in a programming lan-
guage. For example, the real customer Hans Meier has a digital equivalent in the form of a
digital object “Hans Meier.” The actually existing customer (Mr. Hans Meier) is replicated in
the form of a “digital object” in the relevant programming language of the IT system. In
this digital replication, however, only the most important attributes are included, such as
first name and last name, birthdate, or sex. In most cases attributes such as hair color, eye
color, or color of clothing will not be relevant as they are not needed to perform the tasks
of the system.

Class A class in object-oriented programming provides the structure that is needed for the crea-
This is a structure that is tion of a digital object. Any desired number of objects can be created with a class as a
used to create digital
objects which are the cen- basis. All objects created from one class will have the same structure, i.e., the same attrib-
tral elements in the utes and methods. A class is thus roughly comparable to a Word document template, and
object-oriented SW devel- an object is a Word document that is created from this template. Which classes an object-
opment process.
oriented system consists of and what the structure of the required classes looks like will
be determined in the object-oriented design phase. The starting point for the design are
the identified and specified requirements. Object-oriented programming for IT systems
consists (almost) exclusively of the implementation of classes. That is, the developer
defines the structure of classes, i.e., which elements (attributes and methods) make up
the objects that are created from the classes. An object-oriented system then creates the
appropriate objects where they are needed, e.g., from database entries or user inputs. The
description of the classes guarantees that all objects that are created based on these

24
classes behave identically. All objects of the same class have the same attributes and can
use the same functions and routines (the “methods”). All objects created from the same
class can thus be processed by the functions of the system in the same way.

The main tasks in the analysis, and later in the design, are the identification and descrip-
tion of classes. Although the approach is called “object orientation,” it is actually the
classes that play a prominent role in the approach.

For the analysis and design of the online shop, Ms. Koch therefore must first identify
appropriate classes which will later serve as a template for programming the online shop.

2.2 Identifying Classes


In the first step, an analysis model of the system is created which will be used, during Analysis model
analysis, to define what a system should do and then on that basis to later define, during This is the result of the
object-oriented analysis,
design, which classes the system should consist of. Possible candidates for classes must which is used for commu-
be identified and listed based on the defined problem statement and the requirements. nication between the
developers and the client
and/or the users of the
An established procedure for the identification of classes can be described as follows: system.

1. Mark all nouns in a problem statement as candidates for classes.


2. Check whether the nouns that have been identified can be described using other
nouns or if they have associations or dependencies with other nouns. If one of the two
statements is true, the noun is modeled as a class.
3. If the noun is used to add details to another noun, it is modeled as an attribute of a
class.
4. Check all remaining words that are neither a class nor an attribute for relevance and,
if necessary, remove them from the list of candidates for classes.

Example

The products that Mr. Lange sells in the online shop will be media of all types, in particular
books, music products, films, and games. Each product has a manufacturer, a title, and a
product number. Books and games have an author, films have a director, and music prod-
ucts have a performer.

Step 1: After listing all of the nouns, the list will consist of the following entries (the nouns
are listed in singular form only):

• online shop
• product
• media
• type
• book
• music product
• film

25
• game
• manufacturer
• title
• product number
• author
• director
• performer

Steps 2–4: Check candidate for class, attribute, and relevance in general.

• Online shop: not relevant because it designates the system as a whole


• Product: relevant as class
• Media: not relevant because it only describes a product
• Type: not relevant because it only describes a product
• Book: relevant as class because it is refined by attributes
• Music product: relevant as class because it is refined by attributes
• Film: relevant as class because it is refined by attributes
• Game: relevant as class because it is refined by attributes
• Manufacturer: relevant as attribute because it fits description of classes
• Title: relevant as attribute because it fits description of classes
• Product number: relevant as attribute it fits because description of classes
• Author: relevant as attribute because it fits description of classes
• Director: relevant as attribute because it fits description of classes
• Performer: relevant as attribute because it fits description of classes

The figure below shows the identified classes of an example scenario. Classes are always
shown in the form of a rectangle. The name of the class is written in the rectangle.

Figure 5: Identified Classes

Source: Brückmann & Dreikauss, 2020.

26
2.3 Attributes as Properties of Classes
As described above, classes (and thus also objects) consist of attributes and methods. The
attributes (also: property of classes) are static elements of classes. Concrete values of the
object can be saved in an attribute. Attributes are used exclusively for saving values and
can be understood as free memory inside of an object. In summary, the values of all attrib-
utes of an object describe its state. Objects that have been created from the same class
and whose attributes have the exact same values, are identical.

Example

A class “Customer” was identified for the online shop. For each customer, the last name,
first name, birthdate, and sex must be saved. Last name, first name, birthdate, and sex are
thus modeled as attributes of the class “Customer.”

Figure 6: Attributes of the “Customer” Class

Source: Brückmann & Dreikauss, 2020.

As shown in the figure above, attributes are listed in a separate rectangle below the class
name. A class with attributes thus consists of two adjacent rectangles: The top rectangle
contains the name of the class and in the bottom rectangle the attributes of a class are
listed.

When modeling attributes, the properties described in the table below, among others, can
be defined. Of these properties, the name, at a minimum, is required in an analysis model.
The other properties can also be defined now, but this is not mandatory. The remaining
properties will be defined during the course of the SW development process.

Table 3: Properties of Attributes

Properties of an attribute Description Example

Name Name of the attribute firstname

27
Properties of an attribute Description Example

Data type Defines how the values of the Date (date)


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

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


the attribute can change or not

Default value Specifies the default value of the 2020-01-01


attribute

Source: Brückmann & Dreikauss, 2020.

Example

After identifying possible classes, now the attributes of the classes must be identified.
Good candidates for attributes are nouns that can be used for describing or adding details
to other nouns. In the figure below, the attributes identified in the example scenario
online shop are added.

Figure 7: Identified Attributes of the Classes

Source: Brückmann & Dreikauss, 2020.

2.4 Methods as Functions of Classes


Methods Methods (also: functions, operations) are dynamic elements of classes. They contain algo-
These are dynamic ele- rithms, statements, and processing specifications that can be used to create, calculate,
ments of classes and
describe the behavior of modify, and delete values. The results of the methods can be saved in attributes of the
classes such as defining class or in newly created objects. Methods are used to describe the behavior of objects,
specifications for the cal- i.e., what an object does. Methods can thus be used to program calculations of values and
culation, modification,
and creation of attributes the application of business rules or specifications in the creation and deletion of objects.
and objects.

28
When modeling methods, the elements described in the table below can be defined. The
name, at a minimum, is required in an analysis model. Detailed information on the return
value, parameters, and the function of the method can also be added one by one over the
course of the development process.

Table 4: Properties of Methods

Elements of methods Description Example

Name Name of the method getLastname()

Parameter Required objects and values that (Date birthdate), (String


are needed for processing the lastname, String firstname)
method (Integer number1, Integer
number2)

Return value Defines the data type of the Date


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

Source: Brückmann & Dreikauss, 2020.

Example

We now need to define the methods for the class “Customer” that was provided with
attributes above. What is important here is that in each case the values stored in the
attributes can be read again. As described above, it is only possible to access attributes
from outside via methods, and never directly. Therefore the class “Customer” has to sup-
ply for each of its attributes a method that returns the current value of the attribute.

Figure 8: Attributes and Methods of the “Customer” Class

Source: Brückmann & Dreikauss, 2020.

29
As shown in the figure above, the methods of a class are modeled in an additional rectan-
gle below the attributes. A class with methods thus consists of three adjacent rectangles:
The top rectangle contains the name of the class, the middle rectangle contains the list of
attributes of a class, and the bottom rectangle contains the list of the methods of a class.

2.5 Associations between Classes


All of the elements of an object-oriented system are programmed in the form of classes.
Interaction between different classes is only possible when, during the development proc-
Associations ess, associations have been defined between classes. In addition, cooperation between
These describe depend- objects is only possible when associations have been defined between classes.
encies and relationships
between classes, thereby
enabling cooperation Typical associations between classes are shown in the following table.
between objects.

Table 5: Typical Associations between Classes

Association types Description Example

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


fact that one class “has” or A contract has insurance conditions.
“knows” another class. A calendar has months.
A seller knows their customers.

“consists of” This relationship expresses the rela- A car consists of an engine, 4 wheels, 3
tionship in which a class is part of doors, 1 transmission, and 2 seats.
another class. It is used when a class is A house consists of a roof, 23 windows,
a larger construct with elements that 2 doors,
cannot be described using simple 6 rooms, and 1 stairwell.
attributes.

“is a” This type of relationship expresses the A passenger car is an automobile.


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

Source: Brückmann & Dreikauss, 2020.

Lines and arrows are drawn between the relevant classes so that relationships can be
graphically represented in addition to classes, attributes, and methods. The simplest way
to create relationships is with a continuous line connecting the two classes. Additional
information can be added to the relationship, in addition to the continuous line, as shown
in the table below.

30
Figure 9: Representing Relationships

Source: Brückmann & Dreikauss, 2020.

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

31
Figure 10: Multiplicities in Relationships

Source: Brückmann & Dreikauss, 2020.

Example

To identify and add possible associations to the “online shop” example scenario, we must
return to the original text:

“The products that are sold by Mr. Lange in the online shop should be media of all types,
i.e., books, music products, films, and games. Each product has a manufacturer, a title,
and a product number. Books and games have an author, films have a director, and music
products have a performer.”

These are represented graphically in the figure below. Other than the “is a” associations of
the class “Product” with the classes “Book,” “Music product,” “Game,” and “Film,” no other
associations are currently needed.

32
Figure 11: Example Scenario with Additional Associations

Source: Brückmann & Dreikauss, 2020.

2.6 Unified Modeling Language (UML)


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

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

33
Figure 12: Overview of UML Diagram Types

Source: Brückmann & Dreikauss, 2020.

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

34
Figure 13: Objects and Classes

Source: Brückmann & Dreikauss, 2020.

With the modeling concepts class, object, attribute, method, and association, we have
thus far discussed the basic notation elements. All other notations, such as inheritance or
interfaces, are based on these basic elements, which will be introduced later when they
are needed for object-oriented programming.

SUMMARY
Before programming, both the problem and the design of the object-ori-
ented system are modeled in the phases object-oriented analysis (OOA)
and object-oriented design (OOD). Here, classes are modeled with their
attributes and methods as well as associations between classes with
UML class diagrams.

Possible candidates for classes are identified through an analysis of the


problem based on the relevant nouns. Next, these classes are extended
by adding attributes and methods as required by the problem.

After the identification of attributes, these can be characterized more


precisely with a name, a data type, the information as to whether it is a
constant, and if applicable a default value. Methods, on the other hand,
are described by their name, required parameters, and their return
value.

35
UNIT 3
PROGRAMMING CLASSES IN JAVA

STUDY GOALS

On completion of this unit, you will have learned …

– what elements are required to run and program Java applications.


– which basic elements a Java class consists of and how to program them in Java.
– how attributes of classes are programmed in Java.
– how methods of classes are programmed in Java.
– how to specify what a Java program should execute when it starts.
3. PROGRAMMING CLASSES IN JAVA

Case Study
Once Ms. Koch has developed an object-oriented model for the makeup and structure of
the online shop, she would like to take the first steps towards object-oriented program-
ming. Now that she understands that object-oriented systems consist of a set of cooperat-
ing objects, she wants to know how to create classes and objects with the Java program-
ming language and what preliminary steps she needs to take.

3.1 Introduction to the Java


Programming Language
Programming In simple terms, programming (also: implementation) consists of three different activi-
This activity has the goal ties:
of developing program
code that can be execu-
ted as a program or pro- 1. Programming, i.e., production of program code (also: source code, source text, pro-
gram component after gram text)
compilation on a com-
puter. 2. Compiling, i.e., automatic translation of the program code produced into a form that
can be executed by a computer
3. Executing a program, i.e., starting and running the generated and compiled program
code to see whether the system performs as expected

While the program code can be written with a simple text editor, software will be needed
by no later than the time of translating (also: compiling) the program text written by the
developer into executable machine code. This translation software is called a compiler.
Compiler Compilers are available for every programming language. When the program text has
This is software that been compiled by the compiler, it can be started and executed in a runtime environment.
translates program code
into a form that can be For many programming languages, the operating system of a PC (e.g., Windows, Linux,
executed by a computer. MacOS) provides the runtime environment. Because operating systems have different
functions and properties, programs have to be reprogrammed/recompiled for each oper-
ating system. In the example shown below are all the required elements for development
with the C programming language.

38
Figure 14: Development with the C Programming Language

Source: Brückmann & Dreikauss, 2020.

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


program written in Java does not have to be changed for each operating system. Java dif-
fers from other programming languages in that a Java runtime environment (JRE) must be
installed on devices before you can run a Java program. The Java compiler translates the
programmed source text into what is called “bytecode.” This bytecode is then loaded, Bytecode
started, and executed by the Java runtime environment. Because a Java runtime environ- This is the form a Java
program takes after it has
ment is available for virtually every operating system, a Java program can run on a Linux, been compiled, which can
Windows, or Mac computer. The figure below provides an overview of required elements be executed as a program
in development with Java. In contrast to the figure above, here an additional runtime from a Java runtime envi-
ronment (JRE).
environment is required to allow execution on different platforms.

39
Figure 15: Development with the Java Programming Language

Source: Brückmann & Dreikauss, 2020.

The Java runtime environment (JRE) is required to run a Java program as a user. The Java
Java virtual machine runtime environment consists of the Java virtual machine (JVM) and the Java class
(JVM) library. The JVM is the software that interprets the bytecode and both starts it and runs it
This is an operating sys-
tem-specific software that on the operating system being used. The Java class library provides functions that are
can run Java programs in already part of the Java programming language so that commonly used data structures
bytecode form on a com- (e.g., lists or strings) can be reused by the programmer, but without having to be reimple-
puter.
mented each time.

To develop software in the Java programming language as a software developer, a Java


Java software devel- software development kit (Java SDK) is required. The Java SDK consists of a Java com-
opment kit (Java SDK) piler, a Java virtual machine, the Java class library, and other tools.
This is a basic tool for a
Java developer. It
includes a compiler,
which generates bytecode
and a JVM for running
Java programs. TIP
To facilitate the development process, applications called integrated develop-
ment environments (IDE) are used. For Java, there are for example, Eclipse, Net-
Beans, IntelliJ, or BlueJ as free IDEs—but there several others available.

Your tutor will provide recommendations with download links and instructions
so that you can follow examples and find practical exercises.

40
3.2 Basic Elements of a Class in Java
A class in the programming language Java has a unique name and can contain attributes
and methods. The program code of a class is saved in Java in a text file with the file ending
*.java. A separate file is created for each class. For each class (and for each Java file), the
Java compiler creates a class with the ending *.class in which the compiled bytecode of a
class is saved.

In the figure below the basic structure of the Java class “Customer” is shown again,
although here without attributes. To create a class, the following four elements at a mini-
mum are required: the visibility modifier, the class keyword, the name of the class, and a
few curly braces.

Figure 16: Structure of the “Customer” Class

Source: Brückmann & Dreikauss, 2020.

The class “Customer” can be used as shown in the figure above—the Java compiler would
not return an error during translation into bytecode. In the table below the elements of
the basic structure are described in greater detail:

Table 6: Basic Elements of a Class in Java

Element of a class Description Example

Visibility modifier Defines the visibility of the class for other public
classes

Keyword for the class declara- Indicates to the Java compiler that a Java class
tion class is programmed in the following

Class name Defines the name for the class and is used Customer
as a file name. The class “Customer” is pro-
grammed in a text file “[Link]”

41
Element of a class Description Example

Curly brackets Marks the contents of a class (attributes { … }


and methods); everything inside the braces
belongs to a class

Source: Brückmann & Dreikauss, 2020.

The following rules apply for the name of the class:

• Begins with an upper case letter


• Consists of Unicode characters (with restrictions, e.g., no empty characters, no umlauts)
• Can theoretically be of any length (only limited by the maximum length of a file name)
• Cannot be a keyword (e.g., class or public)
• If the class name contains multiple words, these are combined without separator (e.g.,
WordWord, NameOfClass)

3.3 Attributes in Java


After programming the first basic structure of the class “Customer,” the required attributes
should now be added. The figure below shows the class “Customer” with the attributes
added. An attribute in Java is described with the following elements at a minimum: the
visibility modifier, the data type, and the attribute name. The string data type shown
below is used for strings.

42
Figure 17: “Customer” Class with Attributes Added

Source: Brückmann & Dreikauss, 2020.

In addition, values can already be assigned for attributes during programming (also:
default values). In the following example, two attributes are shown for which a default Default value
value is assigned to each in the source code: A value that is assigned to
an attribute automati-
cally when the object is
• private boolean isPremiumCustomer = false; created is a default value.
• private int quantityOfPurchases= 0;

The elements of the basic structure are described in greater detail in the table below:

Table 7: Basic Elements of an Attribute in Java

Element of an attribute Description Example

Visibility modifier Defines the visibility of the private


attribute for other classes

Data type of the attribute Defines the data type of the String customer
attribute and thereby deter-
mines the number and type of
values that can be stored in the
attribute.
A data type is either a primitive
data type or a class, which is
called a reference data type
(e.g., String or Customer).

43
Element of an attribute Description Example

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

Default value Defines the initial value of the =0


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

Semicolon Marks the end of the attribute ;


declaration.

Source: Brückmann & Dreikauss, 2020.

The following rules apply for the name of an attribute of a class:

• Begins with a lower case letter


• Consists of Unicode characters (with restrictions, e.g., no empty characters, no umlauts)
• Can theoretically be of any length
• Cannot be a keyword (e.g., public or class)
• Is case sensitive (i.e., name is a different attribute than nAme)
• If the attribute name contains multiple words, these are combined without separator
(e.g., attributeAttribute, nameOfCustomer)

3.4 Methods in Java


With the knowledge acquired thus far we can now program simple classes with attributes.
We can now already store data in objects in the form of attribute values. Next, methods
will be implemented which, as dynamic elements of classes, can create, calculate, modify,
and delete the values of attributes.

As previously noted, access to the attributes of an object by other objects is only possible
through methods, but never through a direct access to the attributes of another class
Principle of data encap- (encapsulation principle). Therefore, methods are also needed to read the values of
sulation attributes and make them available to other classes.
Here, an object can never
directly access attributes
of another object. Read- In the figure below, a fully implemented class “Customer” is shown in which the elements
ing or changing attributes of a method are explained using the method getLastname().
should only be possible
through methods.

44
Figure 18: Methods of the “Customer” Class

Source: Brückmann & Dreikauss, 2020.

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

Table 8: Basic Elements of a Method in Java

Element of a method Description Example

Visibility modifier Defines the visibility of the public


method for other classes

45
Element of a method Description Example

Return data type of the method Defines the data type of the String customer void
object in which the result of the
method is output after process-
ing the method body.
Here, a primitive data type or a
class (e.g., string or customer) is
declared. When the method
does not output a result, the
return data type is set to void.

Method name Defines the name for the getLastname() getFirstname()


method; a method name can
only be used more than once in
a class if the number or
data type of the parameters are
different

Parameter list List of required objects and their (Date birthdate), (String last-
data types which are needed for name, String firstname)
processing the method; if no (Integer number1, Integer num-
parameters are defined, the list ber2)
remains empty ()

Method body Contains the specific statements result = number1 + number2;


for what is done when the return lastname;
method is invoked and in what
order.
Each statement ends with a
semicolon “;”, therefore the “;”
in method bodies is often the
last character of a program line.
The statements in a method
body are processed in sequence
from the top down.
If a return data type is defined
for the method, the last state-
ment of the method body
begins with the keyword return.

Source: Brückmann & Dreikauss, 2020.

The following rules apply for the name of the method:

• Begins with a lower case letter


• Consists of Unicode characters (with restrictions, e.g., no empty characters, no umlauts)
• Can theoretically be of any length
• Cannot be a keyword (e.g., public or class)
• Is case sensitive (i.e., method() is a different method than mEthod)

Signature An additional concept for methods in Java is the signature. Methods can be uniquely
A signature uniquely identified using their signature. The signature of a method consists of the name of the
identifies a method and
consists of the name of method and the parameter list. The return data type is not a part of the signature. Each
the method and the signature can only occur once in a class since only then can the JRE determine which
parameter list. method should be invoked and processed at the runtime of the program. In other words,
the name of a method can be assigned more than once in a class as long as the parameter
list is different.

46
CODE EXAMPLE 1
Here, the names and the signatures are different:

public void login () {…}

public void logoff () {…}

CODE EXAMPLE 2
Here, both the parameter lists and the signatures are different:

public int addtoShoppingCart (Product product) {…}

public int addtoShoppingCart (Product product, int quantity) {…}

CODE EXAMPLE 3
Here, only the return data types are different, but not the method names or the
parameter lists. The signatures are identical:

public boolean pay (boolean test) {…}

public void pay (boolean test) {…}

To access the attributes of a class, any number of method names can be assigned. How-
ever, in general, names should be chosen so that it is easy to recognize what the method
actually does. Getter and setter methods are used for writing and reading attributes. A Getter and setter
getter method returns the value of an attribute. A setter method changes the value of an methods
These are special meth-
attribute to the value that is passed as a parameter to the setter method. ods used for reading,
changing attributes, and
implementing the princi-
Example ple of data encapsulation.

A class “Customer” fully modeled with getter and setter methods is shown in the figure
below. It makes it possible both to access the saved values of the attributes (via the getter
methods) and to change the values (via the setter methods).

47
Figure 19: Getter and Setter Methods for the “Customer” Class

Source: Brückmann & Dreikauss, 2020.

A relevant implementation is also shown in the figure below using the example of the
attribute. For all other attributes, the implementation of the getter and setter methods is
similar; only the names of the methods and parameters are different. The basic structure,
however, remains the same. Nonetheless, please note here that in the following figure the
parameter of the setter method setLastname was named with lastname just as with the
class private attribute lastname—which does not strictly have to be done this way. But to
differentiate between these two in such a case, the keyword this is used here, which can
be used to refer to the object itself and thus to the class attribute ([Link]).

48
Figure 20: Implementation of Getter and Setter Methods for the Attribute of the
“Customer” Class

Source: Brückmann & Dreikauss, 2020.

To execute the statements implemented in a method body, the relevant method must be
invoked. Methods can be invoked from within other method bodies of the same class or
from method bodies of another class. A method is invoked using the name.

CODE EXAMPLE 1
Invocation of the method getLastname() inside the class “Customer”

String id1= getLastname();

Here, the getter method of the attribute lastname is invoked to store the value of
lastname in a local variable id1.

CODE EXAMPLE 2
Invocation of the method setLastname() inside the class “Customer”

setLastname(“Lange”);

Here, the setter method of the attribute lastname is invoked to change the cur-
rent value of lastname to the value “Lange”.

49
CODE EXAMPLE 3
Invocation of the method getLastname() of the class “Customer” from another
class

String id2= [Link]();

The object that invokes the method getLastname() in Customer has stored an
object of the class “Customer” under the variable customer1. By invoking cus-
[Link]() it is possible to invoke the specific method getLastname()
in the object customer1. The value of [Link]() is stored in the
invoking class in the variable id2.

CODE EXAMPLE 4
Invocation of the method getLastname() from another class

[Link](“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
[Link](“Lange”) it is possible to invoke the specific method
setLastname(String name) in the object customer1. With this method invoca-
tion, the “Lange” from another object can be stored as an attribute in the object
customer1.

Method overloading Method overloading means that there are methods in a class with the same name. With
This process is used to overloading, i.e., multiple instances of a method with the same name, you have the ability
implement multiple
methods with the same as developer to define various method behaviors based on the given parameters.
name but different
parameter lists inside a
class. Example

The following method in Mr. Lange's online shop should be used to place a product in the
shopping cart. The method provided for this purpose—addToShoppingCart—contains an
appropriate product as a parameter. The product is an object from the class “Product.”

public void addToShoppingCart (Product product) {…}

But in addition to this method, it should also be possible to place more than one of the
same product in the shopping cart. For this purpose, the method addToShoppingCart is
overloaded by implementing a second method addToShoppingCart which also expects
the quantity of the products being added as a parameter, in addition to the product.

50
public void addToShoppingCart (Product product, int quantity) {…}

3.5 Main Method: Starting Point of a Java


Program
As described above, a consistent implementation of object orientation requires breaking
problems down into different classes of a UML class diagram. A Java program likewise
consists of a combination of different classes that cooperate together through the invoca-
tion of methods. In a Java program, objects are generated from classes at runtime, which
in turn can generate additional objects. Therefore, a currently running Java program can
be conceived as a network of interrelated objects.

For each Java program, however, there is a fixed starting point, i.e., a very specific method
is always invoked first when the program starts: the main method. The generation of all
the objects that are required by the program starts inside this method. The main method
is declared as shown in the figure below.

Figure 21: Main Method as the Starting Point of a Class

Source: Brückmann & Dreikauss, 2020.

The following elements of the main method should be used without changes:

• visibility modifier (public),


• declaration of the main method as static method (static),
• specification that there is no return type (void),
• name of method (main), and
• parameter list (String args[]).

51
Only the method body is modified as necessary. The developer can freely decide which
class of the program the main method is implemented in. To prevent confusion, however,
there should only be one class with a main method.

Example

A small first prototype of the online shop is shown in the figure below as a class diagram. A
class “OnlineShop” has no attributes, but it does have a main method. The class “Cus-
tomer” has four attributes and the particular getter and setter methods.

Figure 22: Main Method in a Class Diagram

Source: Brückmann & Dreikauss, 2020.

An appropriate example implementation of the class “OnlineShop” with the main method
is shown in the figure below. When executing the program “OnlineShop,” two objects of
the type “customer” are created in the method body of the same method. They are then
assigned to the variables customer1 and customer2 and the values for the attributes last-
name and firstname respectively are saved in the two objects. Then, the value of the
attribute lastname for the object customer1 is output in the console. Next, the attribute
lastname of customer1 is set to a new value and the current value of lastname is output in
the console both for customer1 and customer2.

52
Figure 23: Example on How to Implement a Main Method

Source: Brückmann & Dreikauss, 2020.

53
As shown in the example, the program “Online Shop” starts with the main method of the
class “OnlineShop.” Starting in the main method, two concrete customers are now cre-
ated, i.e., objects of the type customer are created and stored as a variable customer1 and
customer2 for subsequent use in the main method of OnlineShop.

SUMMARY
The Java programming language is a platform-independent program-
ming language. By using OS-specific Java runtime environments, a Java
program can be run on virtually any operating system without customi-
zation.

As in object-oriented modeling, Java classes consist of attributes and


methods, along with their unique name. Unlike modeling, however, in
Java programming there are special conventions and rules that must be
followed. For attributes, a visibility modifier—name that is unique
throughout the class—and a valid data type must be defined.

The following rules apply when programming methods: The signature of


a method (name and parameter list) must be unique throughout the
class. Each method must also have a declared return data type (or:
void), a visibility modifier, and an implemented method body. The pro-
gramming in the method body defines what the method does, or more
exactly it defines the statements and processing specifications.

Access to attributes through another object is usually realized with get-


ter and setter methods. This allows for consistent adherence to the prin-
ciple of data encapsulation.

Methods can be overloaded, i.e., multiple methods that have the same
name and differ only in the parameter list can be used.

A Java program is always started from the main method. This method is
the starting point for all of the activities and sequences in the program.
When a class contains a main method that is declared in accordance
with conventions, this automatically determines where the program will
begin processing statements.

54
UNIT 4
JAVA LANGUAGE CONSTRUCTS

STUDY GOALS

On completion of this unit, you will have learned …

– what primitive data types Java has and what value range they cover.
– how variables can be temporarily stored with values.
– what important operators exist in Java and how they are used.
– what control structures are available and how statements can be repeated for control
purposes.
– how the visibility of classes and their elements can be defined in targeted ways using
packages.
4. JAVA LANGUAGE CONSTRUCTS

Case Study
Ms. Koch is now ready to implement the elements of a UML class model in Java program
code. This means that she can program classes with their attributes in Java and she also
knows how to declare methods. Though she is generally familiar with the main method,
she is not yet familiar with the elements of the Java programming language that she can
use to implement algorithms and business rules inside of a method body.

4.1 Primitive Data Types


Information in object-oriented programming is generally stored in attributes of objects.
The data type of an attribute determines what information can be stored in an attribute. If
the name of a class is defined as the data type of an attribute, then only objects of this
class can be assigned as concrete values to this attribute.

Primitive data types But with primitive data types there are a number of very simple data types in Java that
These are data types are not described by their own class.
whose values are not
objects, e.g., simple num-
bers or logical values. Primitive data types are used to store logical values (true, false), integers (1, 12, 13131),
floating point numbers (1.123, 21234.1232) and single characters (t, w, f, d). Primitive data
types are simple standard data types that also exist in other programming languages. An
overview of primitive data types in Java is shown in the table below.

Table 9: Primitive Data Types in Java

Type of saved Keyword in


values Java Description Examples

Logical values boolean Can either be true or false. true


Other values are not allowed. false

Integer byte 8-bit value range from 123, 0, 23, 120


–128 to 127

short 16-bit value range from –23000, 0, 13231


–32,768 to 32,767

int 32-bit value range from –12332123, 234,


–2,147,483,648 to 2,147,483,647 1102379239

long 64-bit value range from 8347829790645,


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

56
Type of saved Keyword in
values Java Description Examples

Floating point float 32-bit value range from 1.87236f (simple number
number 1.40239846*10–45 to with decimal point and
3.40282347*1038 appended “f”);
–3.938e12f (
–3.938*1012 with appen-
ded “f”)

double 64-bit value range from 1.87236d (Simple number


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

Character char A single Unicode character. In ’A’ (= letter A),


addition to numerals, letters, and ’2’ (= numeral 2),
symbols, also includes control ’\n’ (= control character
characters such as blanks, tabula- line break)
tor, and line break.

Source: Brückmann & Dreikauss, 2020.

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

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

Table 10: String as Data Type for Strings

Type of saved val-


ues Keyword in Java Description Examples

Strings String Used to save strings of any "online",


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

Source: Brückmann & Dreikauss, 2020.

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.

57
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, variables can only be
used inside the method body. Therefore they do not require a visibility modifier.

In the top section of the figure below is an example of the declaration of five variables.
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.

Figure 24: Declaration and Assignment of Variables

Source: Brückmann & Dreikauss, 2020.

At the bottom of the figure above is an example of the assignment of values to four varia-
bles. 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.

58
Figure 25: Summary of Declaration and Assignment

Source: Brückmann & Dreikauss, 2020.

4.3 Operators and Expressions


Operators can be used to calculate and change values that are stored in variables and
attributes. The Java programming language supports a range of arithmetic and logical
operators for this purpose. The main arithmetic operators are shown in the table below. Arithmetic operators
Generally, the data type of the result of an operator is determined by the operand with the Operators for executing
mathematical functions
largest value range. such as addition, subtrac-
tion, division, and multi-
plication.
Table 11: Important Arithmetic Operators

Operation Operator Can be used with data types Example

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


variable by the value 1 float b = 3f; b++;

Arithmetic addition; + Integers, floating point numbers int c,d,e;


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

Arithmetic subtraction - Integers, floating point numbers int e = 3; float f


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

Arithmetic multiplica- · Integers, floating point numbers int c,d;


tion c = 3;
d = c * 4;

59
Operation Operator Can be used with data types Example

Arithmetic division; / Integers: If both operands are int h = 4;


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

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


remainder operator or = 5;
modulus/modulo int m;
operator); calculates m = k % l;
the remainder of the
arithmetic division

Source: Brückmann & Dreikauss, 2020.

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

Table 12: Important Logical Operators

Can be used with


Operation Operator data types Example

Logical complement ! boolean boolean b1;


(negation); changes boolean b2 = false;
the truth value of the b1 = !b2;
operand

Logical AND; returns && boolean boolean b3;


true when both oper- boolean b4 = true; boolean
ands are true b5 = true;
b3 = b4 && b5;

Logical OR; returns || boolean boolean b6;


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

Exclusive OR; returns ^ boolean boolean b9;


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

Source: Brückmann & Dreikauss, 2020.

Relational operators Relational operators compare expressions against each other and return boolean as the
These are operators used result type. That is, they either return true or false. Like logical operators, relational opera-
to run functions for com-
parison of values and tors are commonly used to manage control structures. The table below provides an over-
object references. view of frequently used relational operators:

60
Table 13: Important Relational Operators

Can be used with


Operation Operator data types Example

Equality primitive == Primitive data types int z1, z2;


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

Non-equality Primi- != Primitive data types int z3, z4;


tive data types: Reference data types boolean e3;
returns true if the z3 = 4;
values of the oper- z4 = 3;
ands are not equal. e3 = z3 != z4;
Reference data types: Customer customer3,
Returns true if the
customer4;
two operands contain
boolean e4;
different references.
customer3 = new Customer();
customer4 = new Customer();
e4 = customer3 !=
customer4;

Less than: returns < Integers, floating int z5, z6;


true if the value of point numbers boolean e5;
the operand on the z5 = 4;
left is less than the z6 = 5;
value of the operand e5 = z5 < z6;
on the right.

Less than or equal to: <= Integers, floating int z5, z6;
returns true if the point numbers boolean e5;
value of the operand z5 = 4;
on the left is less than z6 = 5;
or equal to the value e5 = z5 <= z6;
of the operand on the
right.

Greater than: returns > Integers, floating int z7, z8;


true if the value of point numbers boolean e6;
the operand on the z7 = 6;
left is greater than the z8 = 5;
value of the operand e6 = z7 > z8;
on the right.

Greater than or equal >= Integers, floating int z7, z8;


to: returns true if the point numbers boolean e6;
value of the operand z7 = 6;
on the left is greater z8 = 5;
than or equal to the e6 = z7 >= z8;
value of the operand
on the right.

61
Can be used with
Operation Operator data types Example

Type comparison: instanceof Reference data types Customer k1;


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

Source: Brückmann & Dreikauss, 2020.

Equality test operators Special equality test operators are the test for equality (==) and the test for non-equality
These are relational oper- (!=). In the case of these operators, the operands determine how the comparison is made.
ators used to run func-
tions that test for equality A basic distinction is made between the comparison of primitive data types and of refer-
or non-equality in which ence data types. If both operands are primitive data types, then the values of the operands
operands determine are compared directly. The figure below shows an example of the comparison of primitive
whether values or refer-
ences are compared. data types where the result (e1) is output in the console. In this case e1 has the value true.

Figure 26: Example of the Comparison of Primitive Data Types

Source: Brückmann & Dreikauss, 2020.

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 “cus-
tomer” is saved. The comparison of k3 and k4 for “reference equality” thus returns the
value false.

62
Figure 27: Example of the Comparison of Reference Data Types

Source: Brückmann & Dreikauss, 2020.

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.

Figure 28: Equality of Reference Data Types

Source: Brückmann & Dreikauss, 2020.

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

Joining strings (con- + String String s1, s2, s3, s4;


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

Source: Brückmann & Dreikauss, 2020.

4.4 Control Structures


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

Control structures The controlled repeat execution of statements is enabled using control structures. The
These are elements of a most important of the Java-supported control structures are
programming language
for conditional or nested
execution of statements. • conditional branches (if-else) and
• loops (for, while, do-while).

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 meth-
ods for attributes of the type boolean begin “is” instead of “get.”) What is initially of inter-
est is the implementation of the method calculateSum(Customer) of the class “Shopping-
Cart.”

64
Figure 29: Class Diagram with the “Shopping Cart” and “Customer” Classes

Source: Brückmann & Dreikauss, 2020.

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 branches. This is a control structure
that is used to execute
A price reduction will either be granted or not depending on the status of the customer. statements using condi-
The structure of a conditional branch in Java appears as shown below: tions.

Code
if(condition) {
Statement1;
}
else {
Statement2;
}

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.

65
Figure 30: Use Case for Conditional Branches

Source: Brückmann & Dreikauss, 2020.

Figure 31: Example of Simple Conditional Branches

Source: Brückmann & Dreikauss, 2020.

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


class “ShoppingCart” that contains a simple conditional branch. In this method, the sum
of a shopping cart is calculated according to the attribute premiumcustomer. If the cus-
tomer is a premium customer, then the sum is reduced by 10%. If not, the sum does not

66
change. With a conditional branch, either the statements in the “if block” or the state-
ments in the “else block” are executed. Never are both blocks executed. The “else block” is
optional and can also be omitted depending on the problem.

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

Figure 32: Use Case for Nested Branches

Source: Brückmann & Dreikauss, 2020.

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

67
Figure 33: Example of Nested Branches

Source: Brückmann & Dreikauss, 2020.

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

68
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.

Figure 34: Example for if-else if-else Branches

Source: Brückmann & Dreikauss, 2020.

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 state- They are a control struc-
ture used for executing
ments. The number of iterations of the loop is determined by the satisfaction of a loop statements repeatedly.
condition (also: running condition, exit condition). There are three different types of loops:

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

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

Code
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 statement 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 controlling 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.

Figure 35: Example of a while Loop

Source: Brückmann & Dreikauss, 2020.

Do-while loop The do-while loop is a post-checked while loop. The statements in the loop are always
This is a post-checked executed at least once. Only then is the loop condition tested. If the condition is true, the
loop; statements are exe-
cuted at least 1x and the statements in the loop are executed again; if not, the loop ends. The structure of a do-
condition is tested before while loop is shown below:
a second iteration.

70
Code
do {
Statements;
} 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.

Figure 36: Example of a do-while Loop

Source: Brückmann & Dreikauss, 2020.

In contrast to the while loop and the do-while loop, in the case of the for loop, the initiali- For loop
zation, condition test, and the changing of counter variables are elements of the loop The for loop is a pre-
checked loop in which the
head. As in the while loop, the for loop is a pre-checked loop, i.e., the truth of the condi- head, in addition to the
tion is tested before the initial execution of the loop. condition, also contains
the statements for initiali-
zation of the counter vari-
The structure of a for loop can appear as follows: ables and their incremen-
tation.

Code
for(initialization; condition; loop increment) {
statements;
}

The area up to the first semicolon “;” of the head of the loop is reserved for the initializa-
tion of the counter variables. The loop condition is in the area between the first and sec-
ond semicolon “;”. The area between the second semicolon and the end bracket “)” is
where the counter variables are changed.

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

1. Execute statement for initialization


2. Test the condition
3. Evaluate the condition
1. If condition true: Execute all statements in the for loop
2. If condition false: Abort and no execution of statements

71
4. Execute the statement in the loop increment
5. Continue with #2 (test condition)

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

Figure 37: Example of a for Loop

Source: Brückmann & Dreikauss, 2020.

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 exam-
ple 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.

72
Figure 38: Example for Nested Control Structures

Source: Brückmann & Dreikauss, 2020.

4.5 Packages and Visibility Modifiers


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

73
Figure 39: Packages of the Online Shop

Source: Brückmann & Dreikauss, 2020.

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 package
overview in the figure above. The class declaration comes after the specification of the
package.

Figure 40: Declaration of the Package of a Class

Source: Brückmann & Dreikauss, 2020.

74
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/[Link]” in the package “[Link].”

Class names must be unique within a package. The complete name of a class (the “quali-
fied 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 “[Link].” At the same time, for example, there can also
be a class “Customer” in a library system that has the name “[Link].”

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

Table 15: Visibility Modifiers

Description Can be used with Example

The element is visible to all Classes, attributes, meth- public class Order {}
classes in the program. ods public void calculateSum() {}

The element is only visible in the Classes, attributes, meth- class Order {}
same package. ods void calculate Sum() {}

The element is only visible in the Attributes, methods protected void calculateSum()
same package or derived {}
classes. protected int quantityProduct;

The element is only visible for Attributes, methods private void calculateSum() {}
elements of the same class. private int quantityProduct;

Source: Brückmann & Dreikauss, 2020.

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.

75
UNIT 5
INHERITANCE

STUDY GOALS

On completion of this unit, you will have learned …

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


– how inheritance is expressed in UML class diagrams.
– the difference between a superclass and subclass.
– how inheritance between Java classes is expressed.
– what is meant by overriding inherited attributes and methods.
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.

Figure 41: Implemented Classes

Source: Brückmann & Dreikauss, 2020.

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.”

Figure 42: Example Scenario Completed by Relations

Source: Brückmann & Dreikauss, 2020.

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

5.1 Modeling and Inheritance in the Class


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

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

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

Figure 43: Equal Attributes are Combined in the Superclass

Source: Brückmann & Dreikauss, 2020.

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

Superclass The class “Product” in the example is classified as a superclass and the other classes are
This is the designation for classified as “subclasses.” “Base class” is another term that is commonly used for super-
a class from which other
classes are derived. class and subclass is frequently also called a “derived class.” A subclass is also described
as being derived from a superclass.

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 the
A subclass is derived from superclass, but in addition define other attributes that are important for their own
a superclass and inherits
its attributes and meth- description. For the description of a book, the author is important, but for the sale of the
ods. It specializes a super- book “as a product” manufacturer, title, and product number are sufficient.
class by implementing an
improved functionality
with additional attributes So, the inheritance relationship is used to model more specific classes of another class. In
and methods. the example, the class “Product” is modeled to speak generally about elements of an
order. Here, it is not a question of the exact properties of the actual product, but it is
important to know for the display on the website whether a particular product is a book or
another type of product. On the particular product page the specific properties of a prod-
uct are important, e.g., the author of a book or the performer of a music product.

80
Figure 44: Different Pages for Different Kinds of Products

Source: Brückmann & Dreikauss, 2020.

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 be Inheritance
conveyed about things either generally or specifically while avoiding redundancy. This type of relationship
enables the abstraction of
common attributes in a
The inheritance relationship is transitive, meaning the attributes of an ancestor class are superclass, thereby
passed down to all child classes. A “Product” is also a further specialization of the class reducing repetition in
design.
“Book,” since “Book” is itself a “Product.” In the example shown in the figure below, “non-
fiction book” inherits all the attributes from both “product” and “book.”

81
Figure 45: Transitive Properties of Inheritance

Source: Brückmann & Dreikauss, 2020.

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.

Figure 46: Inheritance of Associations

Source: Brückmann & Dreikauss, 2020.

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

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


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

By grouping shared features together and deriving specialized classes, there is a possibil-
ity of new classes being introduced to the model that have not been identified during the
analysis phase. This is not a problem as long as it ensures that the model is of a managea-
ble 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 possi-
ble that the programming language in which the modeled system is implemented will not
support multiple inheritances. Java, for example, does not support it.

5.2 Programming Inheritance in Java


In Java, inheritance is implemented with a new keyword in the declaration of a class.
Unlike the previously introduced concepts “derivation” or “specialization,” in Java the
concept is called extension. A subclass “extends” a superclass when it defines, or modi- Extension
fies, new attributes and methods; thus, the keyword is extends. In Java, the concept of
extension is used for the
implementation of inheri-
The inheritance relationship in Java starts from the derived class, just like the direction of tance. A subclass special-
the association arrow in UML class diagrams. In Java inheritance is expressed by stating in izes its superclass with
new and adapted func-
the class declaration of the subclass which superclass it is being derived from. tionality.

The subclass inherits all the attributes and methods of the superclass. An exception are
attributes and methods that have been declared private in the superclass. These are also
unavailable in a subclass. But otherwise, inherited attributes and methods retain their vis-
ibility. Attributes and methods are declared public and remain public.

83
Figure 47: Inheritance in Java with extends in the Class Declaration

Source: Brückmann & Dreikauss, 2020.

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.

Figure 48: Derivation of the “Book” Class from the “Product” Class

Source: Brückmann & Dreikauss, 2020.

84
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 val-
ues from the superclass. When invoking inherited methods, the implementations from the
superclass are used.

Figure 49: Invoking Inherited Methods

Source: Brückmann & Dreikauss, 2020.

In the figure above, a book object is generated and both the new attribute and the inheri-
ted 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 it.
This is called assignment compatibility: Each book is a product and can be handled as Assignment compati-
such. bility
This means that a varia-
ble of the type of a super-
But in reverse, there is no such compatibility: Not every product is a book. Looking again class can also be assigned
at the class diagram “Equal attributes are combined in the superclass,” the difference is subclass objects.

clear. The class “Book” declares a new attribute that is not present in the product. The
instantiated product object thus cannot be treated like a book in the event that someone
wishes to access the new attribute.

85
Figure 50: Assignment Compatibility

Source: Brückmann & Dreikauss, 2020.

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


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

Figure 51: Availability of Attributes and Methods Dependent on the Type of the Variable

Source: Brückmann & Dreikauss, 2020.

86
The assignment compatibility is used to ensure the loosest possible coupling of individual
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 specifica-
tions by focusing on the functionalities declared in the class “Product.” Thus, additional
subclasses of Product can be created during implementation—for example, for toy—with-
out 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.

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

Source: Brückmann & Dreikauss, 2020.

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 getDescrip-
tion 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 sub-
classes that also have to be output. The subclasses thus have to adapt the implementa-
tion of the inherited method getDescription for their purposes; this process is called over-
riding. Overriding
The process of imple-
menting an inherited
Methods can be overridden in subclasses by creating a method with the same signature method is called overrid-
and implementing a new method body. ing.

87
Figure 53: Overriding an Inherited Method

Source: Brückmann & Dreikauss, 2020.

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


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

Figure 54: Invoking an Overridden Method

Source: Brückmann & Dreikauss, 2020.

When overriding attributes and methods, the original implementation from the superclass
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 can be

88
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 hier-
archy and selects the implementation there.

Figure 55: Super Addresses the Superclass

Source: Brückmann & Dreikauss, 2020.

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.

89
Figure 56: Access to Implementation in the Superclass with super

Source: Brückmann & Dreikauss, 2020.

SUMMARY
The concept of inheritance allows the functionality of existing classes to
be used in new classes and for special applications to be adapted. With
inheritance, a subclass is derived from a superclass. The subclass inher-
its the visible attributes and methods of the superclass.

In UML class diagrams, the inheritance relationship is expressed by


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

In Java, inheritance is expressed with the keyword extends. The same


attributes and methods are available in the instances of the derived
classes as in the instances of the superclass and can be used in exactly
the same way as their own attributes and methods. Therefore, instances
of derived classes can also be assigned to variables, which have been
declared of the type of the superclass. This is called assignment compat-
ibility.

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.

90
UNIT 6
IMPORTANT OBJECT-ORIENTED CONCEPTS

STUDY GOALS

On completion of this unit, you will have learned …

– how to use abstract classes to set limits on which classes instances can be generated
from.
– how to use abstract methods to determine which methods subclasses have to imple-
ment.
– 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.
6. IMPORTANT OBJECT-ORIENTED
CONCEPTS

Case Study
Ms. Koch discusses the project status with her customer Mr. Lange. She reports how she
has implemented the classes “Book,” “Music product,” “Game,” and “Film” as subclasses
of “Product.” Mr. Lange takes particular interest when Ms. Koch explains how the sub-
classes override a method of the superclass in order to create a more detailed description
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 Twitter.

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

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

6.1 Abstract Classes


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

92
Figure 57: The “Product” Superclass and Its Subclasses

Source: Brückmann & Dreikauss, 2020.

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 that Abstract class
no instances of this class can be generated. Specific details are implemented in the This is a class of which
instances cannot be cre-
derived subclasses. ated, where common fea-
tures are grouped
In UML, abstract classes are designated, with the word abstract in curly braces. Alter- together and an interface
that must be supported
nately, the class name can be set in cursive font. by its derived datasets is
defined.
Figure 58: Designation of the “Product” Class as Abstract Class, Two Variations

Source: Brückmann & Dreikauss, 2020.

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 structured
like normal classes.

93
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 key-
word abstract in the class declaration. Nothing has to be changed in the other declara-
tions. But if you now try to create instances of this class, the compiler will return an error.

Figure 59: Designation of an Abstract Class in Java

Source: Brückmann & Dreikauss, 2020.

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
Abstract method method has a signature, but no implementation. Just as there can be no concrete instan-
This method has a signa- ces of abstract classes, abstract methods cannot define method bodies. As a result, a class
ture but no method body
and it defines the func- with one or more abstract methods is not complete. Thus, if a class defines at least one
tionality that must be abstract method, it must also be declared abstract in the class declaration. The abstract
implemented in sub- method must then be implemented in a subclass through overriding.
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 getTwitterDescrip-
tion(). This method is marked as abstract and there is no method body.

94
Figure 60: Designation of an Abstract Method

Source: Brückmann & Dreikauss, 2020.

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.”

Figure 61: Implementation of an Abstract Method by Overriding

Source: Brückmann & Dreikauss, 2020.

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


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

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.

95
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.”

Figure 62: Declaration of Variables of the Type Abstract Class

Source: Brückmann & Dreikauss, 2020.

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 imple-
menting specialized functionality like the creation of brief descriptions where they are
appropriate, such as in special subclasses. But the question arises of which object-orien-
ted concept explains the fact that the correct implementation is always used even though
she sometimes just declares her variables of the type “Product.”

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


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

96
Figure 63: The Different Kinds of Products in the Class Hierarchy Polymorphism
This means that objects
of different classes can be
assigned to a variable
when the classes have an
inheritance relationship
with each other. This way,
it is possible to call differ-
ent method implementa-
tions through the same
variable based on which
object is assigned to the
variables of runtime.

Source: Brückmann & Dreikauss, 2020.

The individual subclasses can override methods in order to specialize behavior. In the
example system, we generally speak of products and demand very specific requirements—
such as, for example, outputting a description text—from them. However, the implementa-
tion of this requirement differs from subclass to subclass. Polymorphism allows all instan-
ces of subclasses to be treated as products as well as access the relevant special imple-
mentation 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 getDescription for
a variable of the type “Product.”

97
Figure 64: Choice of Implementation at Runtime

Source: Brückmann & Dreikauss, 2020.

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


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

But it is also possible to check which class an instance belongs to at runtime. The instan-
ceof operator can be used to run a test of class membership, but this will neutralize the
advantages of polymorphism. Here, you can test for very specific class membership 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 mem-
bership in the class “Book.” If this is the case, special preparations can be made for pro-
cessing a book object; nevertheless, it is worth reflecting on whether these preparations
can also be made from the book object to avoid querying the specific class.

98
Figure 65: Application of the instanceof Operator to Test for Class Membership

Source: Brückmann & Dreikauss, 2020.

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 implementations.
She thus obtains an appropriate description of each product when she calls the method
getDescription.

6.3 Static Attributes and Methods


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

Class variables are also called static attributes since they are not bound to an object but Class variables
are already available from the time a class exists. Static attributes apply to all instances of These attributes are the
same for all instances of a
a class. Their value is shared by all instances of the class. Class variables are declared with class and are addressed
the keyword static. through the class name.

The following figure shows how Ms. Koch declares the class variable descriptionSeparator
as a static attribute of the class “Product.” She can then access this attribute through the
class and does not have to create an object in advance.

99
Figure 66: Declaration and Application of a Static Attribute

Source: Brückmann & Dreikauss, 2020.

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 num-
ber. 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.

100
Figure 67: Declaration and Application of Static Methods

Source: Brückmann & Dreikauss, 2020.

Because static methods can also be invoked without the existence of objects of the partic-
ular 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 constants.
For example, the number Pi and Euler's number e are defined as static attributes of the
class “Math” (see Oracle 2013b).

Figure 68: Static Attributes and Methods of the “Math” Class

Source: Brückmann & Dreikauss, 2020.

101
Examples of static methods are also found in the class “Math.” The results of the methods
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 methods 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 attributes and methods of subclasses. Abstract meth-
ods are methods that have no method body; they are used to force a
subclass to override this method with a concrete implementation. As
soon as a class declares an abstract method, the entire class must be
declared as abstract.

Polymorphism means diversity and allows instances of subclasses of a


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

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

102
UNIT 7
CONSTRUCTORS FOR GENERATING
OBJECTS

STUDY GOALS

On completion of this unit, you will have learned …

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


– how to use different constructors to create objects with specially tailored defaults.
– what issues related to inheritance need to be considered when using constructors.
7. CONSTRUCTORS FOR GENERATING
OBJECTS

Case Study
When creating objects, Ms. Koch has always relied on setting their attributes with getter
and setter methods individually. Occasionally she would encounter errors in doing this, for
example when she forgot to set attributes. In reading about this issue, Ms. Koch discov-
ered 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 constructors by
overloading the standard constructor. She is also familiar with the processing sequence of
the constructors, in case the generated objects are in an inheritance hierarchy. This is rele-
vant, for example, in cases where a reduced minimum order value should be set for pre-
mium customers of the online shop.

7.1 The Standard Constructor


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

104
Figure 69: Utilization of the New Operator in the Main Method of an Auto Management

Source: Brückmann & Dreikauss, 2020.

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 a new
object for a particular
creation of such an object is defined and what exactly happens when you invoke the new class. The constructor is
operator. The standard constructor is used so that you know what values are assigned to invoked for this purpose.
the attributes of a customer object and how to influence this definition. It is invoked
through the new operator and returns the generated object as the result.

You can imagine the standard constructor as a special kind of method that can only exist Standard constructor
once per class. Aside from a few restrictions, the syntax is very similar to a normal method This is a special method
for creating objects of a
(see figure below). class.

105
Figure 70: Definition and Invocation of the Standard Constructor

Source: Brückmann & Dreikauss, 2020.

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:

1. Adapting the default values for primitive data types


2. Creating non-primitive attributes (objects)

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

106
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 constructor is implicitly added by the Java compiler. This means that even Empty standard
though the constructor is not visible in the source text, it can still be invoked with the new constructor
If a constructor is not
operator and it can thus create an object. defined, the compiler
adds an empty standard
When using constructors generally, it should be noted that unneeded objects are automat- constructor.

ically deleted by the Java runtime environment. Here, the term “garbage collection” or Garbage collection
automatic memory management is used. That is, unlike other programming languages This is a concept in the
Java programming lan-
like C/C++ or Objective C, it is normally not necessary to explicitly destroy objects using a guage for automatic
programming statement. The automatic memory management that is integrated in Java memory management.
works very well even when programming with high memory requirements. But when
there is still a need to free up memory, the garbage collector can be invoked with the
statement [Link]().

7.2 Overloading Constructors


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

Figure 71: Online Form to Create a New Customer Account (Left); Possible
Implementation (Right)

Source: Brückmann & Dreikauss, 2020.

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

107
Figure 72: Common Allocation of the Object Attributes by Setter Methods

Source: Brückmann & Dreikauss, 2020.

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 stand-
Overloaded standard ard constructor. This means that a second constructor can be defined in addition to the
constructor standard constructor. This constructor, unlike the standard constructor, has a parameter
Such a constructor is used
to initialize an object with list. With the parameter list, it is now possible to determine precisely which attributes
values that are only deter- should be used to fill the object with information at runtime. The value assignment no
mined at runtime so that, longer has to be manually performed in each affected place using setter methods, but just
in contrast to the stand-
ard constructor, it defines once in the new constructor. Using the familiar example, the figure below shows how the
a parameter list. standard constructor can be overloaded.

108
Figure 73: Example of an Overloaded Standard Constructor

Source: Brückmann & Dreikauss, 2020.

When invoking the constructor, Ms. Koch observes that not much has changed in compari-
son 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 by setter meth-
ods,” 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.

109
Figure 74: Utilization of an Overloaded Constructor as an Alternative to the Application
of Many Setter Methods

Source: Brückmann & Dreikauss, 2020.

An additional problem arises when objects of a class need to be initialized with different
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).

Figure 75: Second, Reduced Input Mask (Left), Possible Implementation (Right)

Source: Brückmann & Dreikauss, 2020.

Unlike the first mask, this mask is used only for managing the most important attributes
(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 over-
loading, it is possible in Java to program any desired number of constructors 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 construc-
tors invoke each other to avoid double code and to improve serviceability. Invoking other

110
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.

Figure 76: Defining a Chain of Overloaded Constructors

Source: Brückmann & Dreikauss, 2020.

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

If in the online shop, for example, a backup copy of a customer should be created, you can
use “copy constructor” (see figure below), which will then be called as follows: Copy constructor
This is used for cloning
objects. It can be pro-
Customer newCustomerObject = new Customer(existingCustomerObject); grammed so that a deep
copy (all reference data
types are also cloned) or
a shallow copy (just prim-
itive data types and
strings are cloned) is cre-
ated.

111
Figure 77: Copy Constructor, Which Can Create a Copy of a Customer Object

Source: Brückmann & Dreikauss, 2020.

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 min-
imum order value. Since, if a customer has an individual minimum order value that is dif-
ferent by 10 euros, an external program or another programmer has to be able to rely on it
being a “genuine” copy constructor.

In this context, the assignment shoppingcart = [Link] should also be recon-


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

shoppingcart = new ShoppingCart([Link])

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

7.3 Constructors and Inheritance


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

112
Figure 78: Extended UML Class Diagram of the Online Shop Example

Source: Brückmann & Dreikauss, 2020.

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

113
Figure 79: Invocation of a Constructor of the Superclass with super()

Source: Brückmann & Dreikauss, 2020.

SUMMARY
Constructors allow a programmer to determine the rules for creating
objects. By overriding the standard constructor, the default values for
primitive data types can be modified. If a class contains attributes with
complex data types, constructors can ensure that instances of such
attributes are always present.

In the event that objects of a class should be created in a different way


depending on the situation, multiple constructors can also be defined.

The different parameter list can then be used to differentiate which con-
structor 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.

114
UNIT 8
HANDLING EXCEPTIONS WITH EXCEPTIONS

STUDY GOALS

On completion of this unit, you will have learned …

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


– what means Java has at its disposal for catching, throwing, or handling exceptions.
– in what cases these means are not sufficient.
– how you can program your own exceptions to cover such cases.
8. HANDLING EXCEPTIONS WITH
EXCEPTIONS

Case Study
Ms. Koch has invested much time in making her programs more robust against errors. To
report such errors back to the calling program components, she devised many different
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 calling
program. Now the time-consuming process of defining and interpreting user-defined error
codes is a thing of the past. To define special error situations and provide them with her
own error message, she can program her own exception classes.

8.1 Typical Scenarios of Exception


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

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

116
Figure 80: Example Scenario for the Exception Handling of Error Signals

Source: Brückmann & Dreikauss, 2020.

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, includ-
ing 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 program-
ming languages without explicit support for exception handling, 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).

117
Figure 81: Handling Error Situations with Signals

Source: Brückmann & Dreikauss, 2020.

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


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

To write more robust programs, there should be a separate channel for signaling errors
that results in the decoupling of domain return values and error signals. A user-defined
data structure for such signals would also have the advantage that it can define differenti-
ated 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 strat-
egies in place for frequent error sources.

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

1. The exception is caught within the method.


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

Table 16: Predefined Standard Exceptions in Java (Excerpt)

Name Description Example

ArithmeticException Division by zero int n = 0;


return 1/n;

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


tion the defined area (more informa- [8];
tion on this below) numbers [10] = 4;

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


object [Link]("Meier");

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

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 Try/catch block
define which exceptions are occurring in the try block, how those exceptions should be Exceptions are caught
with a try/catch block in
caught, and how they should be handled. In the example, the result is set to 0 if no prod- which critical program
uct is in the shopping cart. instructions are con-
tained in the try block
and exceptions are han-
dled in the catch block.

119
Figure 82: Catching Standard Exceptions with try/catch Block

Source: Brückmann & Dreikauss, 2020.

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 excep-
tion handling. Thus, in the following, the second alternative for handling exceptions 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 indicates in that appear in the method (here: ArithmeticException). Using the signature, calling pro-
the method signature
which exceptions can be grams can recognize which exceptions can be expected by this method. Exception han-
thrown by the method. dling by try/catch block must be moved to the calling program. As a result, the example
method pricePerProduct() again becomes significantly more manageable.

120
Figure 83: Second Version: Catching of a Passed Exception

Source: Brückmann & Dreikauss, 2020.

As the calling program, it is now the task of the online shop to catch and handle the excep-
tions. To prevent a possible program abort as shown above, the call of the method price-
PerProduct() is now embedded in a try/catch block. In case of an exception, the error mes-
sage 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 pri-
cePerProduct() indicates that it throws an exception. Such exceptions are called
“unchecked” exceptions in the literature.

121
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 “Prede-
fined 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
Throw therefore presented in the following: Passing the exception with the keyword throw and a
This keyword enables the specific error message. Here, the exception is again caught in the method pricePerProd-
creation of an exception.
uct() via try/catch block in order to then throw a new ArithmeticException that contains
the specific error message. The adapted error message is passed as a parameter to the
constructor of the exception (see figure below).

Figure 84: Third Version: Passing the Exception with Adapted Error Message

Source: Brückmann & Dreikauss, 2020.

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 necessary to
ensure that, in addition to a particular standard exception, all the other exceptions should
also be caught.

122
Let us assume that the method pricePerProduct() is much more complex and, in addition
to the ArithmeticException, can also trigger an ArrayIndexOutOfBoundsException (e.g.,
because the product list needs to be accessed for recalculating the current product 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.

Figure 85: Extended try/catch Block

Source: Brückmann & Dreikauss, 2020.

Exception handling with try/catch blocks offers many advantages, but there is also one sit-
uation 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 neces-

123
sary to ensure that only necessary cleanup tasks are performed. To avoid such redundant
Finally block code, you can use the finally block. It is defined following the catch blocks and is run each
This block contains all time regardless of whether an exception occurs or not (see figure below).
statements regardless of
whether an exception has
occurred in the try/catch Figure 86: Use of the finally Blocks
block or was handled or
not. Here, it is mostly
mandatory cleanup tasks
that are completed.

Source: Brückmann & Dreikauss, 2020.

8.3 Defining Your Own Exceptions


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

124
Figure 87: Definition of User-Defined Exception

Source: Brückmann & Dreikauss, 2020.

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


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

125
Figure 88: Throwing a User-Defined Exception

Source: Brückmann & Dreikauss, 2020.

The method getMinimumordervalue() can now be thrown instead of the error signal Mini-
mumordervalueNegativeException (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 lon-
ger 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 embed-
ded in a try/catch block. In the event of an exception, the related error message is output
in the console.

126
Figure 89: Catching a User-Defined Exception

Source: Brückmann & Dreikauss, 2020.

SUMMARY
With its many exception handling language constructs, Java offers a use-
ful 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-ini-
tialized object. If these are not sufficient, Java allows you to derive
standard exceptions using specially defined exception subclasses with
specific error messages.

127
UNIT 9
PROGRAMMING INTERFACES WITH
INTERFACES

STUDY GOALS

On completion of this unit, you will have learned …

– what interfaces are and what situations they are used in.
– what special characteristics interfaces have in contrast to classes.
– under which rules interfaces are defined.
9. PROGRAMMING INTERFACES WITH
INTERFACES

Case Study
During the development of the online shop, Ms. Koch presented prototypes representing
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 customer 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 prob-
lem. 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 solu-
tions for storing customer data in the online shop. Now, by means of interfaces, she also
has a way to resolve the problem of the multiple inheritance, which is not supported in
Java, and use it to specify software components that are visible to the outside.

9.1 Typical Scenarios of Programming


Interfaces
Gang of four The “gang of four” were already heralding the use of interfaces in 1995. It was better to
A group of four authors program against an interface than against an implementation, was their claim (see
who have written fre-
quently cited literature on Gamma et al., 1995). There are many scenarios where this concept makes sense. Indeed, it
the subject of software ensures a clear separation of the specification and the implementation. This means that
technology. it is possible to neatly separate the process of defining what specific classes or entire pack-
Implementation
ages should be able to do (specification) and how this functionality is to be implemented
This is the technical
implementation (pro- technically (implementation).
gramming) of a predeter-
mined functionality. The
functionality can be
This separation has two advantages: First, it allows for a more flexible software architec-
determined by an inter- ture, as the implementation can be interchanged if necessary without significant adapta-
face, among other things. tion. An example is the print function in text processing: The interface for a print driver is
clearly defined and is known for all printer driver producers. A user can install any drivers
and then select the appropriate printer as needed—be it a PDF printer or an actual printer
(see figure below).

130
Figure 90: Alternative Printer Driver as Example for Flexible Software Architecture

Source: Brückmann & Dreikauss, 2020.

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


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

Figure 91: Reuse by Common Interfaces

Source: Brückmann & Dreikauss, 2020.

TIP
With the introduction of interfaces, an additional instrument is available for uti-
lizing the concept of polymorphism. You have already seen polymorphism at
work in the example of inheritance. There, it was shown how the method of a
superclass was re-implemented in a different way by subclasses. If all the

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

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

Figure 92: Example Scenario for the Use of Interfaces: the Changeable Customer Storage

Source: Brückmann & Dreikauss, 2020.

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

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

Figure 93: Definition and Implementation of an Interface in Java

Source: Brückmann & Dreikauss, 2020.

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 by a Use association
dotted arrow with open head and the stereotype <<use>>, can be used to indicate that a This association indicates
that a class uses an inter-
class is using an interface. This means the class invokes at least one method of the inter- face.
face.

133
Figure 94: Notation of Interfaces in UML

Source: Brückmann & Dreikauss, 2020.

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 administra-
tion and the individual alternatives for long-term storage of customer data. The interface
defines a series of methods that are necessary independent of the implementation 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 realization for each method
that was agreed in the interface ICustomerStorage.

134
Figure 95: Class Diagram for the Use of Interfaces in the Online Shop

Source: Brückmann & Dreikauss, 2020.

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 example
implementation. (For reasons of space, the instructions in the body of the implemented
methods are excluded.)

135
Figure 96: Application, Definition, and Implementation of an Interface in the Online
Shop

Source: Brückmann & Dreikauss, 2020.

Because the methods required for storing customer data are now defined in an interface,
they can be interchanged as often as desired without considerable time and effort (flexi-
bility). 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 inter-
faces can be combined and extended depending on the application with minimal addi-

136
tional 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).

Figure 97: Inheritance of Interfaces Shown by the Example of a Printer Combination


Device

Source: Brückmann & Dreikauss, 2020.

137
The attentive reader will also have noticed that the definition of interfaces is very similar
to abstract classes. There are, in fact, several parallels: Abstract classes can also define
cross-class functionalities using abstract methods. Unlike abstract classes, however, 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 implemented 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 implementation. 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 with-
out significant adaptation for the classes used. On the other hand, it
increases the reusability of classes. This is because an interface imple-
mentation can be used wherever the functionality of the interface is nee-
ded.

138

You might also like