Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
I
ist-4-jav
Manage
Activity
Members
Labels
Plan
Issues
0
Issue boards
Milestones
Wiki
Code
Merge requests
0
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Alice Brenon
ist-4-jav
Commits
3baa81ac
Commit
3baa81ac
authored
3 years ago
by
Alice Brenon
Browse files
Options
Downloads
Patches
Plain Diff
Begining of the slides for class 4
parent
e89c05b4
No related branches found
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
Slides/Class4.md
+434
-3
434 additions, 3 deletions
Slides/Class4.md
with
434 additions
and
3 deletions
Slides/Class4.md
+
434
−
3
View file @
3baa81ac
---
title
:
IST-4-JAV Java Programming
subtitle
:
Slides - Class
4
date
:
2021-10-12
subtitle
:
Class 4 - New heights
author
:
Alice BRENON `<alice.brenon@liris.cnrs.fr>`
date
:
2021-10-19
header-includes
:
\usepackage{fdsymbol}
\usepackage{textgreek}
\usepackage{bclogo}
\usepackage{hyperref}
\usepackage{color}
\definecolor{yellow}{RGB}{255, 127, 0}
\definecolor{greyblue}{RGB}{58, 103, 183}
\hypersetup{
colorlinks,
linkcolor = yellow,
urlcolor = greyblue
}
\usetheme{Frankfurt}
\usecolortheme{seahorse}
---
# Advanced Objects
## Enumerations
### Need
```
Java
class PureBreedCat extends DomesticCat {
String breed;
…
}
```
#### `String` ?
1.
for user: what are the possible values ?
2.
possible errors (case, typos…)
3.
need to validate input
4.
($
\R
ightarrow$ what to do with unexpected values ?)
$
\R
ightarrow$ type too "large"
### A possible solution
:::columns
::::{.column width=40%}
need a finite number of values that are
-
unique
-
easy to compare
-
associated to names
$
\R
ightarrow$ constants of any integral type will do !
::::
::::{.column width=60%}
```
Java
final static byte SIAMESE = 0;
final static byte CHARTREUX = 1;
final static byte SAVANNAH = 2;
…
```
::::
:::
\v
space{0.5cm}
-
1 and 2 are fixed !
-
3 and 4 remain : (
### The `enum` types
-
fixed set of
**symbolic**
constants
-
introduced by
`enum`
instead of
`class`
-
names separated by
`,`
(ended by
`;`
)
-
it's a class like any other ! (fields, methods)
```
Java
enum CatBreed {
SIAMESE, CHARTREUX, SAVANNAH
}
CatBreed breed = CatBreed.SIAMESE;
breed == CatBreed.SAVANNAH; // false
```
### Advanced example
-
optional constructor can't be
`public`
-
all values are constructed statically
-
properties can be initialized
```
Java
enum BreedType {
NATURAL, MUTATION, HYBRID
}
enum CatBreed {
SIAMESE (BreedType.MUTATION),
CHARTREUX (BreedType.NATURAL),
SAVANNAH (BreedType.HYBRID);
private BreedType type;
CatBreed (BreedType type) { this.type = type; }
BreedType getBreedType() { return this.type; }
}
```
## Type variables
## In interface
### Remember containers ?
```
Java
List<Integer>
List<Double>
List<String>
List<List<String>>
…
```
-
a "family" of classes (infinite)
-
work on any type
### Methods signatures
```
Java
List<Integer> ints = new ArrayList<>();
List<String> strings = new ArrayList<>();
for(int i = 0; i < 10; i++) {
ints.add(i);
strings.add(Integer.toString(i));
}
```
$
\r
ightarrow$ what is the signature of
`.add`
?
### An "input"
```
Java
void add(Integer n) // ??
void add(String s) // ??
```
-
type of their methods depend on the type context
-
$
\r
ightarrow$ need to be named in the class declaration
-
"input" of a class, like arguments are the inputs of a function
-
**type variables**
### Generics
-
an identifier (any variable name)
-
inside the "diamond"
`<>`
-
usually a single letter:
+
`N`
$
\r
ightarrow$ "number" type
+
`K`
$
\r
ightarrow$ "key" in an association
+
`V`
$
\r
ightarrow$ "value" in an association
+
`T`
$
\r
ightarrow$ any type
-
multiple parameters are comma separated
`<K, V>`
### May appear
#### in classes
```
Java
class Box<T> {
…
}
```
#### in methods
as the last modifier, just before the return type
```
Java
public <T> List<T> preview(List<T> full, int size);
```
### Wildcards
-
the "unknown type"
-
no name $
\R
ightarrow$ strictly less powerful (!)
-
syntax:
`?`
#### Remark
-
`List<Integer>`
isn't a subtype of
`List<Object>`
-
but it's a subtype of
`List<?>`
!
-
$
\R
ightarrow$ allows to get supertypes !
### Bounds
:::columns
::::column
#### `extends`
-
any type that derives from the given type
-
useful on covariant operations
-
works for generic types
```
Java
<? extends Integer>
```
::::
::::column
#### `super`
-
any type which the given type derives from
-
useful on contravariant operations
-
(only for wildcards ! not generics)
```
Java
<? super Integer>
```
::::
:::
### Useful with interfaces
-
conditions on input types
-
like variables: reusing the name in the same formula makes the types equal
-
hypothesis used in the implementation
-
can be combined with
`&`
:
\
`<T extends Comparable & Number>`
#### Example
sorting requires ordered elements:
```
Java
<T extends Comparable<T>> List<T> sort(List<T> elems);
```
# A little bit of functional programming why not ?
## Functional interfaces
### A key distinction
:::columns
::::{.column width=49%}
#### Regular values
-
data: raw types, objects…
-
can be created dynamically
-
can be stored
-
passed to functions
::::
::::{.column width=1%}
\r
ule{.1mm}{.4
\t
extheight}
::::
::::{.column width=49%}
#### Functions
-
structural unit
-
(similar to loops)
-
no dynamic handling
::::
:::
### But what if we want to…
-
store a function into a variable ?
-
associate it to a key ? (menus…)
-
pass it to another function ?
-
use concurrency (threads) ?
```
Java
boolean isEven(int n) {
return n % 2 == 0;
}
someList.filter(isEven); // Error: cannot find symbol
```
### Interfaces !
-
classes can have (several !) methods
-
passing an object is a way to pass its methods
-
only need a convention to find the method
$
\r
ightarrow$ it's called an interface !
```
Java
interface MyFunctionType {
int run(List<Integer> primes);
}
```
### Representing a function
-
special case: interface with only one method to implement
-
the class is a simple "wrapper" around it
-
conventional name to find it
-
(can have other methods but only 1 abstract)
$
\r
ightarrow$ it's called a functional interface !
**Example**
```
Java
@FunctionalInterface
public interface Predicate<T> {
public boolean test(T t);
}
```
## Lambda expressions
### Concept
:::columns
::::column
#### From the \textlambda-calculus
-
Alonzo Church (1930s)
-
base of many languages: Lisp, Ocaml, Haskell…
-
the set of terms $T$ contain:
+
atoms: constants $C$, variables $V$
+
abstractions: $
\{\l
ambda x.t
\ \f
orall v
\i
n V, t
\i
n T
\}
$
+
applications: $
\{
(t
\
u)
\ \f
orall t, u
\i
n T
\}
$
::::
::::column
-
like functions (arguments mapped to a value)
-
one-liner
-
anonymous
$
\R
ightarrow$ function literals
::::
:::
### Syntax
assuming
-
`(a, b, …)`
is a tuple of $n$ expressions (parentheses optional when 1 only)
-
`e`
is an expression
-
`b`
is a block ending with a
`return`
statement
```
Java
(a, b, …) -> e
(a, b, …) -> { b }
```
are values for a given functional interface
**Example**
```
Java
(n, m) -> n+m
x -> {System.out.println(x); return -x;}
```
### Literal values
**What about their types ?**
-
no "arrow" types in Java so can't really be written "
`int -> String`
"
-
the
`@FunctionalInterface`
are perfect for the job !
-
(mind the conceptual gap)
```
Java
@FunctionalInterface
public interface Endofunction<T> {
T apply(T t);
}
Endofunction<Integer> succ = n -> n+1;
```
### Method reference
-
what about existing functions ?
-
(can be wrapped into a
\t
extlambda, but boring:
```
Java
n -> someObject.someMethod(n)
```
-
can't handle regular functions except to apply them
-
but you can
*refer*
to a method with
`::`
### Example
```
Java
class PartialSum {
private int firstNumber;
PartialSum (int initialValue) {
this.firstNumber = initialValue;
}
public int plus(int secondNumber) {
return this.firstNumber + secondNumber;
}
}
PartialSum two = new PartialSum(2);
Endofunction<Integer> add2 = two::plus;
```
### Use cases
#### "Canned computations"
-
multi-threading (computations in parallel):
`Thread`
-
asynchronous computations:
`Future<T>`
-
(all implement
`Runnable`
)
#### Higher-order operations
-
no variables, lighter to read
-
"add seven to all the elements in this array"
```
Java
int[] newArray = new int[initialArray.length];
for(int i = 0; i < newArray.length; i++) {
newArray[i] = initialArray[i] + 7;
}
```
-
map, reduce, iter…
# Complexity
...
...
@@ -24,4 +446,13 @@ date: 2021-10-12
### Pairs list
**Need:**
### HashMaps
:::columns
::::column
::::
::::column
::::
:::
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment