You are on page 1of 151

Java Advanced Features

Summary
★ Encapsulation ★ Collections (and Maps)
★ Inheritance ★ Annotations
★ Composition ★ Input/Output
★ Polymorphism ★ Concurrency
★ Enums ★ Lambda expressions
★ Abstract class ★ Optionals
★ Interface ★ Streams
★ Exceptions ★ Nested Classes
★ Generic types
3

Encapsulation
Encapsulation is wrapping fields and
methods that will work together as a
single unit. Other classes will not be
able to access fields/methods that
they are not supposed to.

A java class is encapsulated by applying


private modifiers to the fields and
adding public methods or constructors
that are necessary for other classes to
use.
4

Access Modifiers
Java supports four access modifiers that you can use to define the visibility of
classes, methods, and attributes. Each of them specifies a different level of
accessibility, and you can only use one modifier per class, method or attribute. As a
rule of thumb, you should always use the most restrictive modifier that still allows
you to implement your business logic.

These modifiers are, starting from the most to the least restrictive one:
● private
● no modifier
● protected
● public
5

Access Modifiers
6

Encapsulation – getters and setters

Sources Link
7

Encapsulation – constructor
8

Encapsulation – other methods

Sources Link
9

Why Encapsulation?

● Better control of class attributes and methods


● Protects object from unwanted access
● Class attributes can be made read-only (if you only use the get method), or
write-only (if you only use the set method)
● Flexible: the programmer can change one part of the code without affecting other
parts
● Increased security of data
10

Exercises – Salary Increase


Create class Dog.
a) Add private fields to the class, like name, age, gender, race, weight.
b) Create constructor that accepts all of the class fields.
c) Create additional constructor, that will accept only gender and race. It should
call main constructor with default values.
d) Create getters and setters for age and weight.
e) Create object of class Dog. Verify if everything works as expected.
f) Add verification for all arguments passed to the setters. E.g. setWeight method
should not accept values below or equal to 0.
11

Inheritance
A class can inherit from another one by
adding extends keyword
in the class declaration.
• If a class inherits from another one,
it in other words extends it.
• The extended class is called the
parent class (or the base class).
• The class that extends is called the
child class (or the derived class).
• In Java a class can extend only one
class.
12

Inheritance

● Inheritance leads to hierarchies of classes and/or interfaces in an


application
● Object is at the root of Java Class Hierarchy
13

Inheritance

Sources Link
14

Inheritance – overriding methods

Method in base class must not be final.


15

Inheritance – polymorphism

Method in base class must not be final.


16

Inheritance – calling parent’s implementation

Sources Link
17

Inheritance – hiding parent’s fields


18

Inheritance – passing parameters


19

WHY Inheritance ?
1. Frequent use of code written once, i.e. code reusability.

2. One superclass can be used for the number of subclasses in a hierarchy.

3. No changes to be done in all base classes, just do changes in parent class


only.

4. Inheritance is used to generate more dominant objects.

5. Inheritance avoids duplicity and data redundancy.

6. Inheritance is used to avoid space complexity and time complexity.


20

Exercises – Inheritance
Create a Shape class.

a) Add fields, create constructor, getters and setters.


b) Create classes Rectangle and Circle. Both of them should inherit class
Shape.
Which fields and methods are common?
21

Exercises – Inheritance
Create classes Dog and Cat.
a) Move common methods and fields to the class Animal.
b) Create method „yieldVoice”.
c) Create simple array of type Animal, that will contain one object of
type Dog and one object of type Cat.
d) Using for-each loop show which animal gives what kind of voice. How to
print a name of an object?
22

Exercises – Inheritance
Create a class called Employee whose objects are records for an employee.
This class will be a derived class of the class Person which you will have to
copy into a file of your own and compile. An employee record has an employee's
name (inherited from the class Person), an annual salary represented as a single
value of type double, a year the employee started work as a single value of type
int and a national insurance number, which is a value of type String.

Your class should have a reasonable number of constructors and accessor


methods, as well as an equals method. Write another class containing a main
method to fully test your class definition.
23

Exercises – Inheritance
Suggest class structure (UML is optional) that could be used to represent the
following:
(a) A shop is composed of a series of departments, each with its own
manager. There is also a store manager and many shop assistants. Each item sold
has a price and a tax rate.
(b) Vehicles are either motor-driven (cars, trucks, motorbikes) or
human-powered (bikes, skateboards). All cars have 3 or 4 wheels and all bikes
have two wheels. Every vehicle has an owner and a tax disc.
24

Composition
Composition and aggregation means usage of objects as values of fields of
another objects.
Exercises – Composition 25

Write a Java class Author with following features:


Instance variables :
● firstName for the author’s first name of type String.
● lastName for the author’s last name of type String.
Constructor:
● A constructor with parameters, it creates the Author object by setting the two
fields to the passed values.
Instance methods:
● Getters and setters for variables
● toString(): This method printed out author’s name to the screen
Write a Java class Book with following features:
Instance variables :
● title for the title of book of type String.
● author for the author’s name of type String.
● price for the book price of type double.
Constructor:
● A constructor with parameters, it creates the Author object by setting the the
fields to the passed values.
Instance methods:
● Getters and setters for variables
● toString(): This method printed out book’s details to the screen
Write a separate class BookDemo with a main() method creates a Book titled “Developing
Java Software” with authors Russel Winderand price 79.75. Prints the Book’s string
representation to standard output (using System.out.println)

Exercises Link
26

Enums

An enum is a type that has a predefined set of values.


Enum types implicitly extend the Enum class.
27

Enums- EXAMPLE
28

Enums – switch-case

of values.
Enum types implicitly extend the Enum
29

Enums – constructors, fields, methods


30

Enums – methods - EXAMPLE


31

Enums – overriding methods


32

Enums OVERVIEW
33

1. Create enum Planet. Exercises – Enums


a) Override toString method. It should print relative size of a planet
and it’s name.
E.g. „Huge Jupiter”, „Small Pluto”.

b) Create distanceFromEarth method.

c) Verify both methods for multiple planets.


34

Exercises – Enums
2. Create a public enum Weekday with constants for MONDAY, TUESDAY,...
until SUNDAY.The enum should have an instance method boolean
isWeekDay() and an instance method boolean isHoliday().The isHoliday()
method should return the opposite of isWeekDay().

Write a program which demonstrates how this enum could be used,


which has a method which takes a Weekday as the argument and prints a
message depending on whether the Weekday is a holiday or not.
We suggest that the main method loops over all values in the
Weekday enum and sends them as argument to the method.
35

Abstract class
● Abstract class cannot be instantiated.

● It has to be extended to be used.

● Abstract class might include abstract methods – methods without


implementation.

● Fields, non-abstract and static methods work in the same way.


36

Abstract class
37

Abstract class
38

Exercises – Abstract class


1
a. Write an abstract class Shape
– Data members: numSides
– Constructor: initialize numSides
– Concrete method: get method for numSides
– Abstract methods: getArea(), getPerimeter()
b. Write a concrete subclass Rectangle
– Data members: width, height
c. Write a concrete subclass Triangle
– Data members: width, height

In another class, write a main method to define a Rectangle and a


Triangle.
39

Exercises – Abstract class

2. Create an abstract class 'Bank' with an abstract method


'getBalance'. $100, $150 and $200 are deposited in banks A, B and C
respectively. 'BankA', 'BankB' and 'BankC' are subclasses of class
'Bank', each having a method named 'getBalance'.

Call this method by creating an object of each of the three classes.


40

Interface
● Interfaces cannot include fields.

● Might include static methods and fields.

● Methods are public and abstract by default.

● A class can implement many interfaces.

● Might include default implementation (Java 8).

● Interfaces can be extended.


41

Interface
42

INTERFACE
43

Interface – default method


Interface VS ABSTRACT CLASS 44

Overview

The performance of an abstract class is fast. The performance of


interface is slow because it requires time to search actual method in
the corresponding class. It is used to implement the core identity of
class. It is used to implement peripheral abilities of class.
Interface VS ABSTRACT CLASS 45

Overview
46

WHEN Interface ?
1. You expect that unrelated classes would implement your interface. For
example, the interfaces Comparable and Cloneable are implemented by many
unrelated classes.

2. You want to specify the behavior of a particular data type, but not
concerned about who implements its behavior.

3. You want to take advantage of multiple inheritances.


47

WHEN ABSTRACT CLASS ?


1. You want to share code among several closely related classes.

2. You expect that classes that extend your abstract class have many common
methods or fields or require access modifiers other than public (such as
protected and private).

3. You want to declare non-static or non-final fields. This enables you to define
methods that can access and modify the state of the object to which they
belong.
48

WHEN ABSTRACT CLASS ?


1. You want to share code among several closely related classes.

2. You expect that classes that extend your abstract class have many
common methods or fields or require access modifiers other than
public (such as protected and private).

3. You want to declare non-static or non-final fields. This enables


you to define methods that can access and modify the state of the
object to which they belong.
49

Interface – EXERCICES
1. Write a class that implements the CharSequence interface found in
the java.lang package. Your implementation should return the
string backwards. Select one of the sentences from this book to
use as the data. Write a small main method to test your class;
make sure to call all four methods.

2. Suppose you have written a time server that periodically notifies


its clients of the current date and time. Write an interface the
server could use to enforce a particular protocol on its clients.
50

Exceptions
● If a program's execution is disrupted an exception is thrown.

● Exceptions can be caught and handled.

● Exceptions are represented as objects.


51

Exceptions – base hierarchy


Base type for all exceptions is
the Throwable class.
Two types extend Throwable:
● Error – errors are caused
by environment in which
application is running -
program does not want to
handle them.
● Exception – an exception is
thrown due to program's
fault. It makes sense to
handle them. Every
exception caught by a
program will derive from
Exception class.
52

Exception – try-catch
53

Exception – try-catch-finally
54

Exception – multiple catch


55

Exception – catch with muLtiple parameter types


56

Exception – throwing an exception


57

Exception – „throws” in method signature


58

Exception – custom exceptions


59

Exception – autoclosing - TRY WITH RESOURCES


60

Exercises – Exception
1. Write an application that will read the input and print back value
that user provided, use try-catch statements to parse the input, e.g.
I/O:
Input: 10
Output: int -> 10
Input: 10.0
Output: double -> 10.0
Input: „Hello!”
Output: „Hey! That’s not a value! Try once more.”
2. What do you think about raising an exception: when should we raise
an exception and when return Null on method „failure”? Try to implement
one method for each situation.
61

Generic types
A generic type is a generic class or interface that is
parametrized over types.
62

Generic types
63

GENERICS
64

Generic types – „extends” keyword

Sources Link
65

Generic types – generic interface


66

Generic types
There is a convention that the parameterized type name is a single
uppercase letter.

Also there is a convention specifying which letter should be used:


● E, T - element type
● K - key type
● V - value type
● T - type
● N - number type
● S, U, V if there are more parameterized types
67

Exercises – Generic types


1. Create a Person class that will implement a Comparable interface.
Person class should implement compareTo method, that will verify if one
person is taller than another.

2. Create a simple Generic class, that will give a possibility, to


store any kind of value within. Add object of type String, Integer and
Double to array of that Generic type. Print all values of the array
within a loop.
68

Collections

Java offers very useful types that represent collections(sets, lists


etc.).

Three main types are these interfaces:


● Collection represents a collection.
● List – extends Collection, represents an ordered list of elements.
● Set – extends Collection, represents a set of elements
(a set does not contain duplicates, order is not crucial).
● Map represents a dictionary – storage of pairs of keys and values.
69

Collections – hierarchy
70

Collections – hierarchy and implementations


71
List

A List type object is very similar to an array object - it’s


elements have 0-based indices.
List is a generic type, parameterized type represents the type of
it's elements. It includes many useful methods.
List is an interface that extends the Collection interface. To
assign a value to a variable of such type you have to use it's
implementation. There are various implementation of the List interface.
One of them is an ArrayList.
72

Collections – List
73

Collections – List using Iterator


74

ARRAY LIST

Sources Link
75

LINKED LIST

Sources Link
76

LINKED LIST VS ARRAY LIST


COMPLEXITY
77

LIST EXERCICES

1. Create a List and display its result (data should be provided by the
user - console):
a) Purchases to be made. *If an element already exists on the
list, then it should not be added.
b) *Add to the example above the possibility of "deleting"
purchased elements
c) Display only those purchases that start with „m” (e.g. milk)
d) * View only purchases whose next product on the list starts
with „m” (e.g. eggs, if milk was next on the list)

2. Ratings received. Display their average. The numbers can not be less
than 1 and greater than 6.

3. * List of lists - multiplication table


78

Collections – Set

Set is an interface that extends Collection interface.

A set either contains an element or it doesn't – an element cannot be


present in a set multiple times.

Set is a generic interface (parameterized type is the type of elements).


If we want to get a Set instance, we need it's implementation. We will use
the HashSet class.
79

Collections – Set
80

Collections – Set
81

Exercises – Set
1. Create a set consisting of colors - given from the user.

2. Present the removal of individual elements from the set.

3. Display the collection before and after sorting.


82

Collections – Map
A Map is an object that maps keys to values. A map cannot contain
duplicate keys: each key can map at most to one value.
83

Collections – Map
84

Collections – HASHMap
85

Exercises – Map
1. Create a map and display its result (data should be provided by the
user - console):
a) Names and surnames
b) Names and ages.
c) Names and lists of friends (other names).
d) * Names and details (map of maps), e.g.
„Mike”:
„ID”: „...” ,
„birthPlace” : „…”

86

Annotations
● Inform the compiler about code structure.

● Tools can process annotations to generate code, documentation.

● Annotations can be processed during runtime, e.g. classes can be


found by their annotations.
87

Annotations
Annotation is a java type. It is used by writing "@" character followed
by annotation's type name.

Annotation @Override informs compiler that method is declared in either


parent class or in implemented interface. It helps to avoid mistakes
when overriding methods.
88

Annotations
Annotations can be parametrized.

In the example annotation will make the compiler assume, that the code
is correct (it will not result in showing warnings).
89

Input/Output
A File object represents a file. It can be created passing the path to
it's constructor. Path can be either absolute or relative.
90

I/O – reading and writing files


91

I/O – reading and writing files


92

I/O – reading and writing files

Sources Link
93

I/O – Serializable
94

I/O – Serializable

Sources Link
95

I/O – Serializable
96

New I/O
Java 8 introduced new classes for reading/writing files.
They are put in the java.nio package.
97

New I/O – reading and writing files

Sources Link
98

New I/O – directories


99

Exercises – I/O and New I/O


1. Create a file with a „lorem ipsum” paragraph within – it can be done
by copy-pasting existing paragraph or generating it dynamically using
Java library. Read that file.
a) Count words.
b) *Count special signs (like comma, dot, spaces).
c) *Select one word and print it’s number of occurrences.
100

Concurrency in Java
Concurrency is ability to perform multiple operations simultaneously.
Maintainer and resources needed to perform a set of operations is
called thread. Every application has at least one thread.
101

PROCESS VS THREAD
Concurrency is ability to perform multiple operations simultaneously.
Maintainer and resources needed to perform a set of operations is
called thread. Every application has at least one thread.
Concurrency 102

Concurrency means that an application is making progress on more than


one task - at the same time or at least seemingly at the same time
(concurrently).
Parallel Execution 103

Parallel execution is when a computer has more than one CPU or CPU
core, and makes progress on more than one task simultaneously. However,
parallel execution is not referring to the same phenomenon as
parallelism.
CONCURRENT VS PARALLEL 104
Parallel Concurrent Execution 105

It is possible to have parallel concurrent execution, where threads are


distributed among multiple CPUs. Thus, the threads executed on the same
CPU are executed concurrently, whereas threads executed on different
CPUs are executed in parallel.
Parallelism 106

The term parallelism means that an application splits its tasks up


into smaller subtasks which can be processed in parallel, for instance
on multiple CPUs at the exact same time. Thus, parallelism does not
refer to the same execution model as parallel concurrent execution -
even if they may look similar on the surface.
107

Concurrency – main thread


If we run an application with the public static void main(String[]
args) method, a thread is created. We will refer to this thread as the
main thread.
108

Concurrency – sleep method


109

Concurrency – NEW THREAD CREATION


110

Concurrency – extending Thread class


111
class
Concurrency – extending Thread
112

Concurrency – extending Thread class


113

Concurrency – extending Thread class

Sources Link
114

Concurrency – implementing Runnable interface


115

Concurrency – implementing Runnable interface


116

EXTENDING THREAD VS Runnable interface


The significant differences between extending Thread class and
implementing Runnable interface:

● When we extend Thread class, we can’t extend any other class even
we require and When we implement Runnable, we can save a space for
our class to extend any other class in future or now.

● When we extend Thread class, each of our thread creates unique


object and associate with it. When we implements Runnable, it
shares the same object to multiple threads.
117

Concurrency – synchronization
118

Concurrency – synchronization
119

Concurrency – synchronization
120

Concurrency – synchronization
121

Concurrency – synchronization
Shared Multiprocessor Architecture 122

As CPUs are capable of carrying out a


significant number of instructions per second,
fetching from RAM is not that ideal for them. To
improve this situation, processors are using tricks
like Out of Order Execution, Branch Prediction,
Speculative Execution, and, of course, Caching.

As different cores execute more instructions


and manipulate more data, they fill up their caches
with more relevant data and instructions. This will
improve the overall performance at the expense of
introducing cache coherence challenges.
123

VOLATILE
124

VOLATILE
The Java volatile keyword is used to mark a Java variable as
"being stored in main memory". More precisely that means, that every
read of a volatile variable will be read from the computer's main
memory, and not from the CPU cache, and that every write to a volatile
variable will be written to main memory, and not just to the CPU cache.

volatile is Not Always Enough

The situation where multiple threads are incrementing the same


counter is exactly such a situation where a volatile variable is not
enough.
ATOMIC 125

Simply put, a shared mutable state very easily leads to problems


when concurrency is involved. If access to shared mutable objects is
not managed properly, applications can quickly become prone to some
hard-to-detect concurrency errors.
126

Exercises – Concurrency
1. Create a class implementing the Runnable interface (implementing the
run method):
a) Inside the run method display „Hello!”
b) Create a class object.
c) Start the thread receiving the created object as a parameter (new
Thread ().start ())
d) Create several objects, run a separate thread for each of them.
e) Add the constructor to the created class, that accepts the int
value.
f) For the displayed data inside the run method, add the received value
(Hello + value).
g) Add a method to the class that will modify the int value.
h) Add a while loop to the run method, inside which it will print the
modified int value every few seconds.
i) Add the ability to disable (gracefully shutdown) the thread. Why
shouldn’t we just „kill” the thread?
127

Exercises – Concurrency

1. *You are the manager. You have 5 employees. Simulate the situation
in which each of them comes at a different time to work.
a) Every employee, after getting to work, displays the information
“<name: I came to work at <time HH:MM>.”
b) Every 10 seconds, the employee displays „name: I’m still working!”
c) Every 30 seconds, we release one of the employees to home (remember
about stopping the thread!) and remove the employee from the „active
employees list”
d) When you release your employee to home, print „, it's time to go
home!”
e) * When you release a given employee, all of the others speed up.
From that moment, display the information about work 2 seconds faster.
f) ** The manager decides in which order release employees (e.g.
through an earlier defined list)
128

Lambda Expression
Java 8 introduced lambda expressions. A lambda expression is a
representation of an implementation of an interface which consists of
only one method.
129
Lambda expression – predicate (functional interface)
130

Lambda expression
131

Lambda expression – function interface

Sources Link
132

Lambda expression – method reference


133

Lambda expression – supplier, consumer

Sources Link
134

Lambda expression – operator


135

Lambda expression – block of code


136

Exercises – Lambda expression


1. Create and present the usage of lambda expressions:
a) Addition, subtraction, multiplication, division.
b) The sum of elements (int type) of the list.
c) Number of words in the input expression (list containing elements of
type String).
d) * List before and after sorting (use the Arrays class and lambda
expressions: String :: compareToIgnoreCase as a comparator)
137

Optionals
Optional class is a wrapper that can be used if we are not sure if a
value is present. It contains a useful set of methods.
138

OPTIONALS
STREAMS 139

Streams (available in Java > 8) can be used to perform operations on


collections with the usage of lambda expressions.

Let's assume we have a list of people. We would like to get the average
age of people named "Thomas". Streams make such operations very easy to
implement.
140

Streams – collect, findFirst, findAny


141

Streams – filter, map


142

Streams – allMatch and anyMatch


143

Streams – reduce method

Sources Link
144

Streams – forEach, sorted


145

Exercises – Streams
1. Using streams, for a given lists:
- [„John”, „Sarah”, „Mark”, „Tyla”, „Ellisha”, „Eamonn”]
- [1, 4, 2346, 123, 76, 11, 0, 0, 62, 23, 50]

a) Sort the list.


b) Print only those names, that start with „E” letter.
c) Print values greater than 30 and lower than 200.
d) Print names uppercase.
e) Remove first and last letter, sort and print names.
f) *Sort backwards by implementing reverse Comparator and using lambda
expression.
146

Nested classes
A nested class can be defined in body of another class.

We will call them inner and outer classes.

Object of non-static inner type is bound to an object of outer type.


147

Nested classes – non-static


148

Nested classes – non-static


149

Nested classes – static


Static nested classes work similarly, the difference is that an
instance of inner static class is not bound to an instance of outer
class.
150

Nested classes – static


151

Nested classes – static

You might also like