Einführung in Java

Werbung
Introduction to Java
• Java Overview
– Language Overview
– Hello World Example
•
•
•
•
Primitive Data Types
Control Structures
Classes in Java
References
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
1
What is Java?
• Java Language
– the specification of a programming language
• Java Virtual Machine (JVM)
– the specification of a virtual machine (byte code)
• Java Library
– the specification of a rich collection of standard APIs
in different flavors
Java
Platform
 Java SE
 Java EE
 Java ME
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
2
From Source to Program
• Source Code
Test.java
– Has to be formulated according to a given syntax
• Compiler
– Checks sources
– Generated byte code
javac
• Byte Code
Test.class
– Code which is readable by the Java Virtual Machine (JVM)
• Interpreter (JVM)
– Reads the class files and executes a program
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
3
Execution Model
Compile-time Environment
Source Code
Hello.java
Source Code
Hello.xxx
Run-time Environment
Java Class
Library (API)
Compiler
javac
local or
through
network
JVM
Class
Loader
Byte Code
Verifier
Interpreter
Byte Code
Hello.class
A Java Program (Applet) runs in the
same process as the browser
=> Security Problem!
24 February 2017
System / OS
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
4
Java Byte-Code Languages
• Scala
– Functional and object-oriented language
• Clojure
– Lisp dialect, supports software transactions
• Groovy
– Scripting language
• Kotlin
– Focus on Android and DSLs
• References
– http://en.wikipedia.org/wiki/List_of_JVM_languages
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
5
Example: Simple Application
• Application
– Runs as a stand-alone program
– Class contains a main method
• Hello.java
public class Hello {
public static void main(String args[]) {
System.out.println("Hello world");
}
}
– Uses Java library (System.out) for printing
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
6
Example: Simple Application
• Compiler:
– javac Hello.java
• Interpreter:
– java Hello
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
7
Byte Code of Hello.class
[00000000]
[00000010]
[00000020]
[00000030]
[00000040]
[00000050]
[00000060]
[00000070]
[00000080]
[00000090]
[000000a0]
[000000b0]
[000000c0]
[000000d0]
[000000e0]
[000000f0]
[00000100]
[00000110]
[00000120]
[00000130]
[00000140]
ca
00
00
56
00
74
0c
72
6c
4f
6e
00
53
6f
70
2f
21
08
05
00
b2
24 February 2017
fe
0d
13
01
16
72
00
6c
6c
62
67
15
74
2f
72
6c
00
00
2a
01
00
ba
00
01
00
28
69
15
64
6f
6a
2f
4c
72
50
69
61
05
01
b7
00
02
b2
12
b6
be 00 00 00 33
0e 08 00 0f 0a
00 06 3c 69 6e
04 43 6f 64 65
5b 4c 6a 61 76
6e 67 3b 29 56
00 16 01 00 0b
07 00 17 0c 00
01 00 10 6a 61
65 63 74 01 00
53 79 73 74 65
6a 61 76 61 2f
65 61 6d 3b 01
72 69 6e 74 53
6e 74 6c 6e 01
6e 67 2f 53 74
00 06 00 00 00
00 09 00 00 00
00 01 b1 00 00
09 00 00 00 15
12 03 b6 00 04
getstatic
00
load constant 03
invoke virtual 04
00
00
69
01
61
0c
48
18
76
10
6d
69
00
74
00
72
00
11
00
00
b1
02
1a
10
74
00
2f
00
65
00
61
6a
01
6f
13
72
15
69
00
00
00
02
00
0a 00 06 00 0c 09
00 11 07 00 12 07
3e 01 00 03 28 29
04 6d 61 69 6e 01
6c 61 6e 67 2f 53
07 00 08 07 00 14
6c 6c 6f 20 77 6f
19 01 00 05 48 65
2f 6c 61 6e 67 2f
61 76 61 2f 6c 61
00 03 6f 75 74 01
2f 50 72 69 6e 74
6a 61 76 61 2f 69
65 61 6d 01 00 07
28 4c 6a 61 76 61
6e 67 3b 29 56 00
02 00 01 00 07 00
01 00 01 00 00 00
00 09 00 0a 00 0b
00 01 00 00 00 09
00 00 00 00 00
load System.out
load "Hello World"
invoke println
rld
Hello Wo
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
8
Decompiling Hello
javap-c-c
Hello
%%javap
Hello
Compiled from
from "Hello.java"
"Hello.java"
Compiled
public class
class Hello
Hello {{
public
public Hello();
Hello();
public
Code:
Code:
0: aload_0
aload_0
0:
1: invokespecial
invokespecial #1
#1
1:
4: return
return
4:
// Method
Method java/lang/Object."<init>":()V
java/lang/Object."<init>":()V
//
public static
static void
void main(java.lang.String[]);
main(java.lang.String[]);
public
Code:
Code:
0: getstatic
getstatic
#2
0:
#2
// get
get Field
Field java/lang/System.out:Ljava/io/PrintStream;
java/lang/System.out:Ljava/io/PrintStream;
//
3: ldc
ldc
#3
3:
#3
// load
load the
the string
string String
String Hello
Hello world
world
//
5: invokevirtual
invokevirtual #4
#4
5:
// Method
Method java/io/PrintStream.println:(Ljava/lang/String;)V
java/io/PrintStream.println:(Ljava/lang/String;)V
//
8: return
return
8:
}}
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
9
Outline
• Java Overview
• Primitive Data Types
– Range
– Operatiors
• Control Structures
• Classes in Java
• References
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
10
Variables
• Variable declaration
– Type Name { , Name} ;
int max, points, mark;
 Naming convention: variable names begin wit a lower-case letter
 Important: name should be meaningful!
• Variable declaration with initialization
int max=36, points=30, mark;
• Assignment
– Variable = Expression;
mark = 1 + 5 * points / max;
• Use of variables in expressions
mark = 1 + 5 * points / max;
System.out.println(mark);
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
11
Primitive Data Types
• Language defined types
–
–
–
–
–
–
boolean
char
byte
short
int
long
– float
– double
24 February 2017
Length in bits
truth values
16-bit Unicode character
8-bit signed integer
16-bit signed integer
32-bit signed integer
64-bit signed integer
8
16
8
16
32
64
32-bit IEEE 754 floating point number
64-bit IEEE 754 floating point number
32
64
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
12
Assignment Compatibility
• Implicit Casts (Automatic Assignments)
byte
short
int
long
float
double
char
int n = 123;
float f = n;
float f = 16777217;
// f = 123.0
// f = 1677216.0
// 16777217 = 0b1000000000000000000000001
• Explicit Casts (with possibility to loose precision)
int n = (int) 3.5;
byte b = (byte) 200;
short s = (short) 32768;
24 February 2017
// n = 3
// b = -56
// s = -32768
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
13
Primitive Types (as sets)
boolean
long
double
int
float
short
char
byte
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
14
Operators
• Two-place arithmetic operators
+
-
*
/
%
• One-place arithmetic operators
+
-
++
--
• Comparison operators
>
>=
<
<=
==
!=
!
(conditional evaluation)
• Logical operators
&&
||
• Operators for bit manipulation
&
|
– Examples:
33 >> 2
~33
24 February 2017
^ (xor) ~ (not) >> (rshift) << (lshift) >>> (rshift)
8
-34
555 & 15
2 | 8
11
10
-33 >> 2 -9
-33 >>> 2 1073741815
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
15
Boolean Operators: And / Or
• Logical And (x && y)
– Conditional evaluation
 second argument is only evaluated if first argument is true
 a && b 
if(a) then b else false;
(x != 0) && (y / x) > 0; // no ArithmeticException
• Logical Or (x || y)
– Conditional evaluation
 Second argument is only evaluated if first argument is false
 a || b 
if(a) then true else b;
(x == 0) || (y / x) <= 0; // no ArithmeticException
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
16
Assignment Operators
• Assignment Operators
=
+=
&=
|=
– Examples:
a += 1
a *= 3/2
-=
^=
*=
<<=
/=
>>=
a = a + 1
a = a * (3 / 2)
not a = a * 3 / 2
%=
>>>=
(a = 5 => a = 6)
(a = 5 => a = 5)
• Assignments are Expressions
– Assignment can be used as expression. Value is assigned value of
expression
c = 3 * (d = a + b + 1);
a = b = c = d = 5
=> a = (b = (c = (d = 5)))
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
17
Outline
• Java Overview
• Primitive Data Types
• Control Structures
– Statements
– Conditional Statements
– Loop Statements
• Classes in Java
• References
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
18
Statement
• Statement :==
|
|
|
|
|
|
|
|
|
|
|
Assignment | MethodInvocation
IncrementExpression | DecrementExpression
{ { Statement } }
if ( Expression ) Statement [else Statement]
for ( ForControl ) Statement
while ( Expression) Statement
do Statement while ( Expression) ;
switch ( Expression ) { { SwitchLabel BlockStatements } }
return [Expression] ;
break [Identifier]
continue [Identifier]
;
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
19
Control Structures: Conditional Statements
• if – else – if - statement
if (boolean expression) {
// statements
} else if (boolean expression) {
// statements
} else {
// statements
}
Is executed if none of the
boolean expressions is
true
• Example
if (x > 0) { sign = 1; }
else if (x < 0) { sign = -1; }
else { sign = 0; }
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
20
Control Structures: Conditional Statements
• switch - statement
switch(expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
24 February 2017
The expression must be of
type byte, char, short, int, long
or String
These statements are
executed if the expression
evaluates to value1.
Do not forget the break
statement, otherwise you "fall
through" the cases!
These statements are
executed if none of the case
values match.
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
21
Control Structures: Repetitive Statements
• while-loop
while (boolean expression) {
// statements
}
The body of the loop is
executed as long as the
boolean expression is true.
In the while-loop the condition is
checked before the loop body
is executed
• do-loop
do {
// statements
} while (boolean expression);
24 February 2017
In the do-loop the condition is
checked after the loop body
has been executed
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
22
Control Structures: Repetitive Statements
• for-loop
for(init; test; update) {
// statements
}
– Def: for(S1;B;S2){S3}  S1; while(B){S3;S2;}
sum = 0;
for(i = 1; i <= n; i++) {
sum += i;
}
– Special cases:
for(;B;)A;
for(i=0;;i++)A;
for(;;)
24 February 2017
sum = 0; i = 1;
while(i <= n) {
sum += i; i++;
}
 while(B)A;
 i=0; while(true){A;i++;}
 while(true);
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
23
Outline
•
•
•
•
Java Overview
Primitive Data Types
Control Structures
Classes in Java
– Instance Fields, Methods and Constructors
– Static Fields, Methods and Constructors
• References
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
24
Classes: Motivation
• Primitive Data Types
– byte, short, int, long, char
– float, double
– boolean
• Structured Data Types: Classes (combines several variables)
– Declaration
class Date {
int day, month, year;
}
 The Elements of this type are called attributes or fields
– Use
Date d = new Date();
d.day = 2; d.month = 10; d.year = 2016;
System.out.println(d.year);
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
Class Instances
• Instances of a class have to be generated before its first use
– Declaration reserves memory for references only (32 bit)
Date d1, d2;
d1
d2
– new Date() expression creates a new instance of type Date
d1 = new Date();
d1.day = 2;
d1
d2
0
2
day
0
10
month
0
2017
year
d1.month = 10;
d1.year = 2017;
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
26
Class Instances
• Classes are blueprints
– Arbitrary many instances can be created
– All fields of a new instance are initialized with zeros, i.e.
 0, 0L, false, \u0000, 0.0, 0.0f
 null
• Assignments
d2 = d1;
d2.day = 8;
 Change of d2.day changes
d1.day as well
d1
d2
8
2
day
10
month
2017
year
d1 = null;
d2 = null;
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
27
Class Instances
• Assignments
– Assignments are only possible, if the types match
class Point {
int x, y;
}
class Rational {
int numer, denom;
}
Point p1 = new Point(), p2 = new Point();
Rational r1 = new Rational(), r2 = new Rational();
p1 =
r1 =
p1 =
p1 =
p1.x
p1.y
24 February 2017
p2; // ok,
r2; // ok,
r1; // not
(Point)r1;
= r1.numer;
= r1.denom;
p1 & p2 refer to the same instance
r1 & r2 refer to the same instance
allowed; types are different
// cast not possible
// ok
// ok
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
28
Class Instances
• Comparisons
– d1 == d2
d1 != d2
– d1 == null
Compares references only!
(in contrast to the primitive types)
Comparison with null reference
d1 != null
– d1.equals(d2);
24 February 2017
Comparison of the content of two
objects
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
29
Classes
• Class = Attributes + Methods
– Attributes = things which the instances (objects) know
 Represents the data (or state) of an object
 Each instance of a class has its own attributes
 Also called:
• Instance fields
• Instance variables
– Methods = things which the instances (objects) can do
 Represents the behavior of an object
 Operate on the object's state
 Every instance has the same methods, but they may behave different
depending on the state of the attributes
 Also called:
• Operations
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
30
Classes in Java
class Date {
private int day, month, year;
public void setDay(int day) { … }
public void setMonth(int month) { … }
public void setYear(int year) { … }
public int getDay() { … }
public int getMonth() { … }
public int getYear() { … }
public int getWeekDay() { … }
public boolean equals(Date date) { … }
}
– Attributes are typically declared private
– Methods are typically declared public
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
31
Classes in UML
• Class = Box with three parts
– Name of the class
– Attributes
– Methods
• Comments
– Visibility
 + = public
 - = private
– Attribute- and Method-part may be omitted
Date
- day: int
- month: int
- year: int
+ setDay(d:int): void
+ setMonth(m:int): void
+ setYear(y:int): void
+ getDay(): int
+ getMonth(): int
+ getYear(): int
+ getWeekDay(): int
+ equals(d:Date): boolean
Date
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
32
Example: Ticket Machine
• Methods
– Represent the operations which
can be applied to an object
• Fields
– Represent the object's state
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
33
Example: Ticket Machine
• Methods (public)
–
–
–
–
–
–
–
–
–
–
Select destination
Select class (1st / 2nd)
Select return / day ticket
Select 1/2-price
Get price
Insert coin
Stamp multi-trip-card
Grab change
Grab ticket
Cancel
There are additional private methods, e.g.
"checkCoin" to check whether a coin is valid
Swiss money.
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
34
Example: Ticket Machine
• Fields (private)
– Destination
– Price (for the selected destination)
 Could also be seen as a public field,
but not changeable from outside)
–
–
–
–
–
halfPrice, firstClass, returnTicket
Value of inserted coins
Tresor of coins
Roll of blank tickets
List of all destinations and base
prices
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
35
Example: Ticket Machine in Java
• Definition
class TicketMachine {
// Methods (incomplete)
public void selectDestination(int plz) { … }
public void setFirstClass(boolean first) { … }
public void setReturnTicket(boolean return) { … }
public void setHalfPrice(boolean halfPrice) { … }
public void insertCoin(Coin amount) { … }
public Ticket grabTicket() { … }
public void cancel() { … }
// State (incomplete)
private int destination;
private int centsEntered;
private Tresor allCoinsInMachine;
private boolean first, halfPrice, returnTicket;
}
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
36
Example: Ticket Machine in Java
• Usage
TicketMachine m;
m = new TicketMachine();
m.selectDestination(8000);
m.insertCoin(new Coin(500));
m.setReturnTicket(true);
m.insertCoin(new Coin(500));
m.setHalfPrice(true);
…
– New instances have to be
created with the new operator
– New instances are created on the
heap
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
37
Example: Ticket Machine as a State Machine
init
selectDestination
cancel
dest
selected
setReturnTicket
setHalfPrice
insertCoin
cancel /
return money
insertCoin
money entered
grabTicket / print ticket
& return change
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
38
Example: Ticket Machine enter Money
• Implementation
void insertCoin(Coin coin) {
centsEntered += coin.getCents();
}
• Specification of Semantics
– Preconditions
have to be established by client
 destination selected
 coin != null
 changeAvailable OR centsEntered + coin.getCents() <= price
– Postconditions
have to be implemented by service provider
 centsEntered = OLD(centsEntered) + coin.getCents()
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
39
Classes: The Concept
• Class as Type
– Specification of the interface, behavior, usage
 Specification of methods using pre- and post-conditions
 Specification of allowed method invocation sequences using state machines
 Specification of the state of a class instance using invariants
• Class as Implementation
– Concrete Implementation of a type
 Fields:
 Methods:
 Constructors:
24 February 2017
Represent the object’s state, available for each instance
Operations which may be applied to class instances
Initialization of new instances
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
40
Classes in Java: Instance Fields
• Declaration & Access
– Available per instance (each instance has a copy of each field)
– Accessible via instance
• Initialization
– Can be initialized in the declaration
– Per default initialized with zero
(0 / 0.0 / false / null)
class Rectangle {
int x, y;
int width = 4, height = 2;
...
}
Rectangle r = new Rectangle();
r.x = 5;
r.width = 10;
r.height = 3;
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
41
Classes in Java: Instance Fields
• Field Types
– Fields may be of primitive type (int, double, char, …)
– Fields may be of reference type (String, …)
public class Person {
String name;
Person[] knows;
}
Cycles: a.knows[0].knows[0].knows[0]….
Alias references:
a.knows[0] == a.knows[1].knows[0]
name
a
name
:String
:Person
:Person
knows
knows
24 February 2017
:String
knows
:Person
name
:String
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
42
Classes in Java: Instance Methods
• Declaration
ResultType Name ( Parameter, Parameter, ...) { Body }
– void result type for procedures
– Method overloading is supported (same name, different parameter types)
• Invocation
– A method is called on
an instance
– A methods has access
to the attributes of the
instance on which it was
called
– Instance on which method
is called is available as
this reference (implicit
argument)
24 February 2017
class Rectangle {
private double w, h;
public void setWidth(double width){
w = width;
}
public double area(){ return w*h; }
}
Rectangle r = new Rectangle();
r.setWidth(10);
double area = r.area();
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
43
Classes in Java:
this is the object on
which the method
was Methods
invoked
Instance
This is the value
of the parameter
class Date {
private int day, month, year;
public void setDay(int day) { this.day = day; }
public void setMonth(int month) { this.month = month; }
public void setYear(int year) { this.year = year; }
public int getDay() { return day; }
Access to the attribute
public int getMonth() { return month; }
year is a synonym for
public int getYear() { return year; }
public int getWeekDay() {
this.year.
int m = month, y = year;
if(m < 3) {y--;} m = (m + 9) % 12;
return (y*1461/4+(m*153+2)/5+day-(y/100*3-5)/4) % 7;
}
public boolean equals(Date d) {
return d != null
&& d.day==day && d.month==month && d.year==year;
}
}
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
44
Classes in Java: Instance Methods
• Parameters: call by value
– Parameters are like local variables declared inside the method
– Assignments made to the parameter are not visible by the calling method
– Changes made on referenced objects are visible by the calling method
public void initDate(Date d, int year) {
d.day = 1; d.month = 1; d.year = year;
}
These changes on d
are visible by the
calling method
public void createDate(Date d) {
d = new Date(); d.day = 1; d.month = 1; d.year = 2011;
}
This assignment on d is NOT visible
by calling method; this method is
useless!
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
45
Classes in Java: Constructors
• Constructors
– Constructor is used to initialize an instance
– Constructor is invoked whenever a new object is created
new Rectangle();
• Constructors
– A constructor is a special method which initializes a new instance




Same name as the class
Without return type / without void !!!
Can have parameters
Can be overloaded (several constructors with different parameter
types)
 First statement in constructor may
call another constructor: this(…):
24 February 2017
• Constructors do not construct,
they initialize only
=>
should have been
called Initializers
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
46
Classes in Java: Constructors
• Example
class Rectangle {
private int x, y, width, height;
public Rectangle(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(Rectangle r) {
// copy constructor
this(r.x, r.y, r.width, r.height);
}
}
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
47
Classes in Java: Constructors
• Default Constructor
– Without the declaration of a constructor a default constructor is defined:
class A {
}
<=>
class A {
public A() { }
}
=> Thus, a new instance of a class without constructor can be
generated this way:
new A();
– As soon as a constructor is defined, the default constructor is no longer
available and has to be provided explicitly if it is needed.
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
48
Classes in Java: Static Fields
• Declaration & Access
–
–
–
–
–
Bound to class (available even if no instance has been created)
Only one copy of the attribute (identical for all instances)
Declaration with static modifier
class Rectangle {
Accessible via class (or instance)
static int nOfInstances = 0;
Initialization per default with zero
Rectangle() { nOfInstances++; }
(0 / 0.0 / false / null)
static
static
static
new
• Constants
– Declaration as static final fields
final int MIN_WIDTH = 0;
final int MIN_HEIGHT = 0;
final Rectangle ZERO =
Rectangle(0,0);
}
Rectangle zero = Rectangle.ZERO;
int r = Rectangle.nOfInstances;
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
49
Classes in Java: Static Methods
• Declaration
static ResultType Name ( Parameter, Parameter, ...) { Body }
– In a static method this is not available
– No access to instance attributes & instance methods in static methods
• Invocation
– Called using class name
(unfortunately class methods
can also be called over an
instance – do not do that)
– Example:
Math.atan2(4, 3);
class Rectangle {
int x, y, width, height;
static Rectangle add(
Rectangle r1, Rectangle r2) {
…
}
}
Rectangle z = Rectangle.add(r1, r2);
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
50
Classes in Java: Static Initialization
• Initialization of class attributes
– Per default, class attributes are initialized with 0/0.0/false/null
– Class attributes can be initialized with the declaration
• Static constructors
class Color {
Color(int r, int g, int b) { … }
static Color black = new Color(0, 0, 0);
static Color[] colors = new Color[3];
– No name, no parameters
– Executed upon loading of the class
static {
colors[0] = black;
colors[1] = new Color(255, 0, 0);
colors[2] = new Color(0, 255, 0);
}
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
51
Class Initialization: What happens when?
• Upon loading of the class
– Static attributes are defined and initialized
 With the value of the initializators (if available)
 With zero (0, 0.0, false, null) per default
– Static constructor is invoked
• Upon creation of a new instance
– Instance attributes are defined and initialized
 With the value of the initializators (if available)
 With zeros (0, 0.0, false, null) per default
– Body of the constructor is invoked
 Other constructors may be invoked with this(…)
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
52
Comparison
delcaration
instance attributes
without static
class attributes
with static
exists
in each object
only once per class
fields are created
whenever an object is created
when the class is loaded
fields are released
from the GC, if no references on
the object exist anymore
when the class is unloaded
(at the end of the program)
constructor is called
when the object is created
when the class is loaded
fields are accessed
obj.field
field / this.field
Class.field
methods are called
24 February 2017
[in methods]
obj.meth()
Class.meth()
meth() / this.meth() [in methods]
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
53
Outline
•
•
•
•
•
Java Overview
Primitive Data Types
Control Structures
Classes in Java
References
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
54
Java Tools
• JDK
– http://www.oracle.com/technetwork/java/javase/
– Downloads
 Java SE 8
 Java SE 8 Documentation
• IDEs
– Eclipse
 http://www.eclipse.org
– IntelliJ
 http://www.jetbrains.com/idea/
– NetBeans
 http://www.netbeans.org
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
55
References
• Core Java: Volume 1: Fundamentals
Cay S. Horstmann & Gary Cornell
Prentice Hall, 10th edition (2015), 1040 pages
ISBN 978-0134177328
http://www.horstmann.com/corejava.html
Accessible over nebis
• Java SE 8 for the Really Impatient
Cay S. Horstmann
Addison Wesley, 1st edition (2014), 215 pages
ISBN 978-0321927767
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
56
References
• Think Java:
How to Think Like a Computer Scientist
Allen Downey and Chris Mayfield
Version 6, 2016
http://www.greenteapress.com/thinkapjava/
• Introduction to Programming Using Java
David J. Eck
Version 7.0, August 2014
http://math.hws.edu/javanotes/
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
57
References (German Java Books)
• Java-Programmierung - Das Handbuch zu Java 8
Guido Krüger & Heiko Hansen
O'Reilly, 8. Auflage (2014), 1104 Seiten
ISBN 978-3955615147
http://www.javabuch.de (7. Auflage online, 2011)
• Java ist auch eine Insel
Christian Ullenboom
Rheinwerk Computing, 11. Auflage, 2014
ISBN978-3836228732
http://openbook.rheinwerk-verlag.de/javainsel/
24 February 2017
(C) Hochschule für Technik
Fachhochschule Nordwestschweiz
58
Herunterladen