Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
new
operator: Creating rectangle
instances
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
null
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
import
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
scale(...)
method
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
getPerimeter()
method
implementation
Lecture notes |
Pdf slides |
|
Rectangle
.getPerimeter()
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Circle
and variable scopes
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Circle
and variable scopes
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Circle
and variable scopes
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Documenting classes and methods
Lecture notes |
Pdf slides |
|
Generated Javadoc
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Generated Javadoc
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Generated Javadoc
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Generated Javadoc
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Generated Javadoc
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Refactoring «r» ⇒ «radius»
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Refactoring «r» ⇒ «radius»
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Refactoring «r» ⇒ «radius»
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Scope assignment problem
Lecture notes |
Pdf slides |
|
this
overriding method
scope
Lecture notes |
Pdf slides |
|
(#1 of 5) |
this
overriding method
scope
Lecture notes |
Pdf slides |
|
(#2 of 5) |
this
overriding method
scope
Lecture notes |
Pdf slides |
|
(#3 of 5) |
this
overriding method
scope
Lecture notes |
Pdf slides |
|
(#4 of 5) |
this
overriding method
scope
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 11) |
Lecture notes |
Pdf slides |
|
(#2 of 11) |
Lecture notes |
Pdf slides |
|
(#3 of 11) |
Lecture notes |
Pdf slides |
|
(#4 of 11) |
Lecture notes |
Pdf slides |
|
(#5 of 11) |
Lecture notes |
Pdf slides |
|
(#6 of 11) |
Lecture notes |
Pdf slides |
|
(#7 of 11) |
Lecture notes |
Pdf slides |
|
(#8 of 11) |
Lecture notes |
Pdf slides |
|
(#9 of 11) |
Lecture notes |
Pdf slides |
|
(#10 of 11) |
Lecture notes |
Pdf slides |
|
(#11 of 11) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
System.out.print(ln)
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 6) |
Lecture notes |
Pdf slides |
|
(#2 of 6) |
Lecture notes |
Pdf slides |
|
(#3 of 6) |
Lecture notes |
Pdf slides |
|
(#4 of 6) |
Lecture notes |
Pdf slides |
|
(#5 of 6) |
Lecture notes |
Pdf slides |
|
(#6 of 6) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
helper-0.9.jar
archive content
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
first-0.9.jar
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
javadoc:javadoc
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 3) |
Lecture notes |
Pdf slides |
|
(#2 of 3) |
Lecture notes |
Pdf slides |
|
(#3 of 3) |
Lecture notes |
Pdf slides |
|
pom.xml
content changes
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 8) |
Lecture notes |
Pdf slides |
|
(#2 of 8) |
Lecture notes |
Pdf slides |
|
(#3 of 8) |
Lecture notes |
Pdf slides |
|
(#4 of 8) |
Lecture notes |
Pdf slides |
|
(#5 of 8) |
Lecture notes |
Pdf slides |
|
(#6 of 8) |
Lecture notes |
Pdf slides |
|
(#7 of 8) |
Lecture notes |
Pdf slides |
|
(#8 of 8) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 8) |
Lecture notes |
Pdf slides |
|
(#2 of 8) |
Lecture notes |
Pdf slides |
|
(#3 of 8) |
Lecture notes |
Pdf slides |
|
(#4 of 8) |
Lecture notes |
Pdf slides |
|
(#5 of 8) |
Lecture notes |
Pdf slides |
|
(#6 of 8) |
Lecture notes |
Pdf slides |
|
(#7 of 8) |
Lecture notes |
Pdf slides |
|
(#8 of 8) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 13) |
Lecture notes |
Pdf slides |
|
(#2 of 13) |
Lecture notes |
Pdf slides |
|
(#3 of 13) |
Lecture notes |
Pdf slides |
|
(#4 of 13) |
Lecture notes |
Pdf slides |
|
(#5 of 13) |
Lecture notes |
Pdf slides |
|
(#6 of 13) |
Lecture notes |
Pdf slides |
|
(#7 of 13) |
Lecture notes |
Pdf slides |
|
(#8 of 13) |
Lecture notes |
Pdf slides |
|
(#9 of 13) |
Lecture notes |
Pdf slides |
|
(#10 of 13) |
Lecture notes |
Pdf slides |
|
(#11 of 13) |
Lecture notes |
Pdf slides |
|
(#12 of 13) |
Lecture notes |
Pdf slides |
|
(#13 of 13) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
float
/ double
!!
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
@Test
annotation
Lecture notes |
Pdf slides |
|
Assert
class
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 4) |
Lecture notes |
Pdf slides |
|
(#2 of 4) |
Lecture notes |
Pdf slides |
|
(#3 of 4) |
Lecture notes |
Pdf slides |
|
(#4 of 4) |
Lecture notes |
Pdf slides |
|
(#1 of 5) |
Lecture notes |
Pdf slides |
|
(#2 of 5) |
Lecture notes |
Pdf slides |
|
(#3 of 5) |
Lecture notes |
Pdf slides |
|
(#4 of 5) |
Lecture notes |
Pdf slides |
|
(#5 of 5) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 6) |
Lecture notes |
Pdf slides |
|
(#2 of 6) |
Lecture notes |
Pdf slides |
|
(#3 of 6) |
Lecture notes |
Pdf slides |
|
(#4 of 6) |
Lecture notes |
Pdf slides |
|
(#5 of 6) |
Lecture notes |
Pdf slides |
|
(#6 of 6) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 6) |
Lecture notes |
Pdf slides |
|
(#2 of 6) |
Lecture notes |
Pdf slides |
|
(#3 of 6) |
Lecture notes |
Pdf slides |
|
(#4 of 6) |
Lecture notes |
Pdf slides |
|
(#5 of 6) |
Lecture notes |
Pdf slides |
|
(#6 of 6) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 7) |
Lecture notes |
Pdf slides |
|
(#2 of 7) |
Lecture notes |
Pdf slides |
|
(#3 of 7) |
Lecture notes |
Pdf slides |
|
(#4 of 7) |
Lecture notes |
Pdf slides |
|
(#5 of 7) |
Lecture notes |
Pdf slides |
|
(#6 of 7) |
Lecture notes |
Pdf slides |
|
(#7 of 7) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 6) |
Lecture notes |
Pdf slides |
|
(#2 of 6) |
Lecture notes |
Pdf slides |
|
(#3 of 6) |
Lecture notes |
Pdf slides |
|
(#4 of 6) |
Lecture notes |
Pdf slides |
|
(#5 of 6) |
Lecture notes |
Pdf slides |
|
(#6 of 6) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
(#1 of 7) |
Lecture notes |
Pdf slides |
|
(#2 of 7) |
Lecture notes |
Pdf slides |
|
(#3 of 7) |
Lecture notes |
Pdf slides |
|
(#4 of 7) |
Lecture notes |
Pdf slides |
|
(#5 of 7) |
Lecture notes |
Pdf slides |
|
(#6 of 7) |
Lecture notes |
Pdf slides |
|
(#7 of 7) |
Lecture notes |
Pdf slides |
|
(#1 of 12) |
Lecture notes |
Pdf slides |
|
(#2 of 12) |
Lecture notes |
Pdf slides |
|
(#3 of 12) |
Lecture notes |
Pdf slides |
|
(#4 of 12) |
Lecture notes |
Pdf slides |
|
(#5 of 12) |
Lecture notes |
Pdf slides |
|
(#6 of 12) |
Lecture notes |
Pdf slides |
|
(#7 of 12) |
Lecture notes |
Pdf slides |
|
(#8 of 12) |
Lecture notes |
Pdf slides |
|
(#9 of 12) |
Lecture notes |
Pdf slides |
|
(#10 of 12) |
Lecture notes |
Pdf slides |
|
(#11 of 12) |
Lecture notes |
Pdf slides |
|
(#12 of 12) |
Lecture notes |
Pdf slides |
|
(#1 of 9) |
Lecture notes |
Pdf slides |
|
(#2 of 9) |
Lecture notes |
Pdf slides |
|
(#3 of 9) |
Lecture notes |
Pdf slides |
|
(#4 of 9) |
Lecture notes |
Pdf slides |
|
(#5 of 9) |
Lecture notes |
Pdf slides |
|
(#6 of 9) |
Lecture notes |
Pdf slides |
|
(#7 of 9) |
Lecture notes |
Pdf slides |
|
(#8 of 9) |
Lecture notes |
Pdf slides |
|
(#9 of 9) |
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
int
representation
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
switch
no longer works
Lecture notes |
Pdf slides |
|
getPrice()
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
private
Day
constructor
Lecture notes |
Pdf slides |
|
Day
instance
creation
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
enum
Day
replacing public class Day
Lecture notes |
Pdf slides |
|
switch
statements working
again
Lecture notes |
Pdf slides |
|
enum
constructor being implicitly
private
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Math.class
and
Print.class
.
Lecture notes |
Pdf slides |
|
Math.class
,
Print.class
and versioning.
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Print.java
manually
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
Lecture notes |
Pdf slides |
|
The concept of classes: Blueprints for objects.
Example: Rectangles
UML diagram visualization.
In object oriented languages classes:
are blueprints for objects.
contain attributes and methods.
allow for implementation hiding.
allow for tailored access to methods and attributes.
|
Classes and creation of related instances.
The «new» operator.
Assignment of attribute values. Working with «null».
Rectangle dashedRectangle = new Rectangle();
Rectangle solidRectangle = new Rectangle();
...
new class-name ([argument 1[, argument 2] ...] )
“Create an instance of class
Rectangle
”.
“Create a Rectangle
object.”
“Create a
Rectangle
”.
Rectangle dashedRectangle = new Rectangle();
dashedRectangle.width = 28;
dashedRectangle.height = 10;
dashedRectangle.hasSolidBorder = false;
Syntax accessing object attributes:
variable.attributeName = value;
|
Exception in thread "main" java.lang.NullPointerException
at de.hdm_stuttgart.mi.classdemo.App.main(App.java:17) |
Rectangle r;
... // possible object assignment to variable r.
if (null == r) {
System.out.println("No rectangle on offer");
} else {
System.out.println("Width:" + r.width);
}
Significance for larger projects.
Fully qualified vs. «import
».
java.lang and other exceptions.
Grouping of related classes (e.g. subsystems).
Structuring big systems.
Provide access restrictions using:
public
, private
and protected
modifier
Resolving class name clashes. Example:
java.lang.String vs. my.personal.String
Package names below java. are reserved.
Package names should not start with javax. either.
Package names must not contain operators:
mi.hdm-stuttgart.de
--> de.hdm_stuttgart.mi.
Packages should start with reversed DNS avoiding clashes.
Bad | Good |
---|---|
import java.util.*; public class Q { public static void main(String[] args) { Scanner s = new Scanner(System.in); Date today = new Date(); } } |
import java.util.Scanner; import java.util.Date; public class Q { public static void main(String[] args) { Scanner s = new Scanner(System.in); Date today = new Date(); } } |
import java.lang.String; ❶ // Optional import java.util.Scanner;❷ // Required public class Q { public static void main(String[] args) { String message = "Hello!"; Scanner ❸ s = new Scanner(System.in); } }
|
Object behaviour, state transitions, derived values.
Selected examples both of state-changing and state-conserving methods.
Rectangle
sample methods.
Example: Scale a rectangle.
Example: Calculate a rectangle's perimeter.
Scale a rectangle and calculate its new perimeter.
|
|
width=66 height=44 |
|
|
Perimeter=110 |
Justifying access restrictions.
public
, protected
«package local»
and private
.
Best practices.
Fine-grained control on attributes and methods.
Support encapsulation / Information hiding.
Purpose: Hide implementation details within class or package
public class DayTime { private int ❶ minutes_since_0_00; public int getMinute() { ❷ return minutes_since_0_00 % 60; } public int getHour() {❷ return minutes_since_0_00 / 60; } } |
public class DayTime { private int minute, hour;❶ public int getMinute() { ❷ return minute; } public int getHour() { ❷ return hour; } } |
No access to private
field of alien
class Time
:
public class Q {
public static void main(String[] args) {
Time t = new Time();
// Error: 'minutes_since_0_00' has private access in 'Time'
t.minutes_since_0_00 = 371;
}
}
Access Level | Other package | Child class | Same package | Same class |
public |
yes | yes | yes | yes |
protected |
no | yes | yes | yes |
Default | no | no | yes | yes |
private |
no | no | no | yes |
Use the most restrictive access level that makes sense for a particular member.
Use private
unless you have a
good reason not to.
Avoid public
fields except for
constants. Public fields tend linking to a particular
implementation and limit your flexibility in changing your
code.
Direct access | Setter access |
---|---|
public class Time {
public int hour, minute;
}
|
public class Time { private int hour, minute; public void setTime(int h, int m) { minute = m; hour = h; } }
|
|
public class Time { private int hour, minute; public void setTime(int h, int m) { minute = m; hour = h; System.out.println("Time has been set to " + hour + ":" + minute); } } |
Direct access | Setter / getter access |
---|---|
final Time time = new Time();
time.minute = 17 * 60 + 45; |
final Time time = new Time();
time.setTime(17, 45); |
Type signatures.
Method signatures: Prerequisite understanding method overloading.
boolean ❶ startsWith(String prefix, int toffset) ❷
Method | Return type | Argument type list |
---|---|---|
void print() |
void | (void) |
int add (int a, int b) |
int | (int, int) |
int max (int a, int b) |
int | (int, int) |
void print (int a, float b) |
void | (int, float) |
void display (float a, int b) |
void | (float, int) |
boolean startsWith❶(String prefix, int toffset) ❷
Method | Method name | Method signature |
---|---|---|
void print() |
(void) | |
int add (int a, int b) |
add | (int, int) |
int max (int a, int b) |
max | (int, int) |
void print (int a, float b) |
(int, float) | |
void display(float a, int b) |
display | (float, int) |
Same name, different argument types.
«C» programming language comparison.
Common examples.
|
|
No argument int value 33 double value 4.333 Two int values -1 and 7 |
Static polymorphism.
Compile time binding.
Early binding.
#include <stdio.h>
void print() {
printf("No argument\n");
}
void print(int i) { /* Error: redefinition of ‘print’ */
printf("int value %d\n", i);
}
void main(void) {
print();
print(33);
}
Code in file print.c |
Compile / execute |
---|---|
|
Compiling > cc -o print print.c |
Executing file
> ./print No argument int value 33 |
public class Person {
String getDetails() { return "dummy";}
int getDetails() { return 1;} // Error: 'getDetails()' is already
} // defined in 'Person'
Return type | Method signature | |
---|---|---|
Method name | Argument type list | |
String | getDetails | (void) |
int | getDetails | (void) |
Only method signature support in Java™ ignoring return type.
In Java™ method signatures allow for uniquely addressing a method within a given class e.g.:
The method named print
having an
int argument followed by a double:
print(int, double)
Combined instance creation and initialization.
Constructors are methods, but ...
Constructor overloading and a class' default constructor.
|
|
Combining statements desired: |
|
---|---|
|
Rectangle r = new Rectangle(28, 10, false);//how ??? |
public class Rectangle { int width, height; boolean hasSolidBorder; ... public ❶ Rectangle ❷ (int width, int height, boolean hasSolidBorder){ this.width = width; this.height = height; this.hasSolidBorder = hasSolidBorder; } }
[access modifier] constructorName (listOfArguments) {
[constructor body]
}
Default constructor e.g. obj = new
MyClass()
.
Non-default constructor e.g. :
obj = new String("xyz");
Can only be executed on object creation.
Are being called prior to any non-constructor method.
Only one of potentially multiple constructors will be executed exactly one time.
However nesting is possible.
|
|
public class Rectangle { int width, height; ┏━▶ public Rectangle(int width, ┃ int height){ ┃ this.width = width; ┃ this.height = height; ┃ } ┃ public Rectangle() { ┣━◀━━ this(1, 1); ❶ ┃ } ┃ public Rectangle( ┃ int widthAndHeight) { ┗━◀━━ this(widthAndHeight, ❷ widthAndHeight); } } |
|
Equivalent: Rectangle r =
new Rectangle(); |
|
---|---|
|
|
|
|
|
Class, method and block scopes.
Documentation, «good» variable names and the this
keyword.
/** Representing circles.
*/
public class Circle {
private double radius;
/** Creating a circle.
* @param r representing the circle's radius
*/
public Circle(double r) {
radius = r;
}
public double getDiameter() {
return 2 * radius;
}
}
/** Representing circles.
*/
public class Circle {
private double radius;
/** Creating a circle.
* @param radius Circle's size
*/
public Circle(double radius) {
radius = radius; // Warning: Variable 'radius' is assigned to itself.
}
public double getDiameter() {
return 2 * radius;
}
}
Motivating class attributes and methods.
Example: A club and its affiliated members.
Syntax of static
and employment
considerations
|
final Helper instance = new Helper(); // Why do we need an instance just for // computing the maximum of two values? System.out.println("Maximum: " + instance.maximum(-3, 5)); |
Maximum: 5 |
Observation: The instance's state is irrelevant for finding the maximum of two values.
Each club member has got a name.
Each member has got an ascending unique membership number.
The overall club's member count needs to be accounted for.
Solution:
Class level: Advance club's member count by each new member.
Instance level: New members receive name and current member count plus 1.
public class ClubMember {
final private String name;
public ClubMember(final String name) {
this.name = name;
}
public String toString() {
return "Member " + name;
}
}
|
Member John Member Karen |
public class ClubMember { static ❶ private int memberCount = 0; final private int memberNumber; ❷ final private String name; public ClubMember(final String name) { this.name = name; memberNumber = ++memberCount; ❸ } public String toString() { return "Member " + name + ", member number " + memberNumber ❹; } }
final ClubMember john = new ClubMember("John"), karen = new ClubMember("Karen"); System.out.println(john); ❶ // toString() is being System.out.println(karen); // called implicitly |
Member John, member number 1 Member Karen, member number 2 |
public class ClubMember { static private int memberCount = 0; ... public ClubMember(final String name) { this.name = name; memberNumber = ++memberCount; } static public int getMemberCount() ❶ { return memberCount; ❷ } ... }
|
Member Karen, member number 2 Club's member count:3 |
{class name}.{variableName}
{class name}.{methodName}([parameter])
public class X { int a; ❶ static int b; ❷
❶ ❷ ❸ System.out.print(...)
Class variable (static) out of type |
|
One of 9
overloaded methods in class |
for
, while
and do
... while
Cross project dependencies.
Repositories and project artifacts.
Automated third-party class import and dependency management
Executing automated tests
Complete project lifecycle:
compile, test, execute, package, deploy
Extensible plugin architecture
Source: CreatePdf.java |
PDF output |
import com.itextpdf.kernel.pdf.PdfDocument; ... final PdfWriter writer = new PdfWriter("helloWorld.pdf"); final PdfDocument pdf = new PdfDocument(writer); final Document document = new Document(pdf, PageSize.A8.rotate()); document.add(new Paragraph("Hello World!"). setFontColor(ColorConstants.MAGENTA). setFontSize(20)); document.close(); |
|
|
mvn dependency:tree
...
--- dependency:3.6.1:tree (default-cli) @ hellopdf ---
de.hdm_stuttgart.mi:hellopdf:jar:0.9
\- com.itextpdf:itext-core:pom:8.0.2:compile
+- com.itextpdf:barcodes:jar:8.0.2:compile
| \- org.slf4j:slf4j-api:jar:1.7.36:compile
+- com.itextpdf:font-asian:jar:8.0.2:compile
+- com.itextpdf:forms:jar:8.0.2:compile
+- com.itextpdf:hyph:jar:8.0.2:compile
+- com.itextpdf:io:jar:8.0.2:compile
| \- com.itextpdf:commons:jar:8.0.2:compile
+- com.itextpdf:kernel:jar:8.0.2:compile ...
mvn archetype:generate [INFO] Scanning for projects... ... 1: remote -> am.ik.archetype:elm-spring-boot-blank-archetype ... 2: remote -> am.ik.archetype:graalvm-blank-archetype ... 3: remote -> am.ik.archetype:graalvm-springmvc-blank-archetype ... ... 2083: remote -> org.apache.maven.archetypes:maven-archetype-quickstart... ... 3330: remote -> za.co.absa.hyperdrive:component-archetype_2.12 (-) Choose a number or apply filter ... |
Helper.java |
pom.xml |
---|---|
package mi.calc.common; public class Helper { static public long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } } |
<project xmlns="http://maven.apache.org...> ... <groupId>mi.calc</groupId> <artifactId>common</artifactId> <version>1.0</version> ... </project> |
goik@goiki Helper> mvn install [INFO] Scanning for projects... [INFO] ------------------------------------------- [INFO] Building helper 0.9 ... [INFO] Installing .../Helper/target/helper-0.9.jar to /ma/goik/.m2/repository/mi/calc/common/1.0/common-1.0.jar
goik@goiki tmp> unzip ...hdm_stuttgart/de/mi/sd1/helper/0.9/helper-0.9.jar
Archive: .../.m2/repository/.../sd1/helper/0.9/helper-0.9.jar
creating: META-INF/
inflating: META-INF/MANIFEST.MF
creating: de/
creating: de/hdm_stuttgart/
creating: de/hdm_stuttgart/mi/
creating: de/hdm_stuttgart/mi/sd1/
inflating: de/hdm_stuttgart/mi/sd1/Helper.class
creating: META-INF/maven/
creating: META-INF/maven/de.hdm_stuttgart.mi.sd1/
creating: META-INF/maven/de.hdm_stuttgart.mi.sd1/helper/
inflating: META-INF/maven/de.hdm_stuttgart.mi.sd1/helper/pom.xml
inflating: META-INF/maven/de.hdm_stuttgart.mi.sd1/helper/pom.properties
<project ...> ... <groupId>de.hdm_stuttgart.mi.sd1</groupId> <artifactId>lottery</artifactId> <version>0.9</version> <packaging>jar</packaging> <name>lottery</name> <dependencies> <dependency> <groupId>de.hdm_stuttgart.mi.sd1</groupId> <artifactId>helper</artifactId> <version>0.9</version> </dependency> ... </project>
static public long binomial(int n, int k) { return (Helper.factorial(n) / Helper.factorial(k) / Helper.factorial(n - k)); } public static void main(String[] args) { System.out.println("There are " + binomial(5, 2) + " ways to draw 2 out of 5 numbers"); System.out.println("There are " + binomial(49, 6) + " ways to draw 6 out of 49 numbers"); }
Download file mavenTemplate.zip
from
here
.
Extract mavenTemplate.zip
to folder
template
.
Optional: Edit template/pom.xml
reflecting your project needs i.e. <groupId>
and related.
Optional: Import your project in Intellij IDEA.
mvn --batch-mode -e archetype:generate \ -DgroupId=de.hdm_stuttgart.mi.sd1 -DartifactId=second -Dversion=0.9 \ -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 [INFO] Scanning for projects... ... [INFO] BUILD SUCCESS ...
See artifact reference.
mvn --batch-mode -e archetype:generate \
-DgroupId=de.hdm_stuttgart.mi.sd1 -DartifactId=second -Dversion=0.9 \
-DarchetypeGroupId=de.hdm_stuttgart.mi -DarchetypeArtifactId=mi-maven-archetype-quickstart -DarchetypeVersion=2.3
[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
...
[INFO] BUILD SUCCESS ...
mvn --batch-mode ❶ -e archetype:generate ❷ \ \ -DarchetypeGroupId=de.hdm_stuttgart.mi \ ❸ -DarchetypeArtifactId=mi-maven-archetype-quickstart \ -DarchetypeVersion=2.3 \ \ -DgroupId=de.hdm_stuttgart.mi.sd1 ❹ \ -DartifactId=first \ -Dversion=0.9
> cd first # Enter project directory > find . -type f # Search recursively for files ./pom.xml ❶ ./src/main/java/de/hdm_stuttgart/mi/sd1/HighlightSample.java ./src/main/java/de/hdm_stuttgart/mi/sd1/Statistics.java ./src/main/java/de/hdm_stuttgart/mi/sd1/App.java ❷ ./src/main/resources/log4j2.xml ./src/test/java/de/hdm_stuttgart/mi/sd1/AppTest.java ./Readme.md
> mvn compile [INFO] Scanning for projects... ... [INFO] Building first 0.9 ... [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to /ma/goik/first/target/classes [INFO] -------------------------------------------------------- [INFO] BUILD SUCCESS
> find target/classes -type f
./target/classes/de/hdm_stuttgart/mi/sd1/App.class
...
> cd target/classes ❶ > java de.hdm_stuttgart.mi.sd1.App ❷ Hi there, let's have fun learning Java! ❸
Change to base directory containing compiled Java™ classes. |
|
Application execution. Note: Our |
|
The expected output result. NoteExecuting this particular class requires a configuration
in our project's ...
<archive>
<manifest>
<mainClass>de.hdm_stuttgart.mi.sd1.test.ShowReachedPoints</mainClass>
</manifest>
</archive> ...
|
> mvn package ... T E S T S ... Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 ... [INFO] Building jar: /ma/goik/first/target/first-0.9.jar ... [INFO] Replacing /ma/goik/first/target/first-0.9.jar with /ma/goik/first/target/first-0.9-shaded.jar ... [INFO] BUILD SUCCESS
java -jar target/first-0.9.jar
Hi there, let's have
fun learning Java!
Remark: This will execute HelloWorld.class
being contained in first-0.9.jar
.
> mvn javadoc:javadoc [INFO] Scanning for projects... ... Generating /ma/goik/First/target/site/apidocs/allclasses-noframe.html... Generating /ma/goik/First/target/site/apidocs/index.html... Generating /ma/goik/First/target/site/apidocs/overview-summary.html... Generating /ma/goik/First/target/site/apidocs/help-doc.html...
See e.g. class String documentation.
> mvn clean
...
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ first ---
[INFO] Deleting /ma/goik/first/target
[INFO] ------------------------------------------------------------------------
[
Built in Maven support in Intellij IDEA.
MI supplementary archetypes require MI archetype configuration in
~/.m2/settings.xml
.
Your Maven project depends on its
pom.xml
file.
Reloading changed pom.xml
file.
Test categories.
Why unit testing? Idea of test «driven development».
Required steps.
Unit test: Test individual methods, classes and packages in isolation.
Integration Test: Test a group of associated components/classes.
Acceptance / Functional Test: Operate on a fully integrated system, testing against the user interface.
Regression Test: Ensure system integrity after (implementation) change.
Load test: Responsiveness vs. system load.
Informal problem specification:
A prime number is a whole number greater than 1 whose only factors are 1 and itself.
Sample values: 2, 3, 5, 7, 11, 13, 17, 23, ...
First write tests, then implement.
Specify but not yet implement classes / methods.
Write skeleton (dummy) implementations.
Write corresponding unit tests.
Implement skeleton.
Test your implementation.
Providing both an implementation and related tests possibly revealing coding flaws.
Providing prime number related tests.
/** * Dealing with prime numbers. */ public class Prime { /** * Check whether a given value is prime or not ❶ * @param value A positive value * @return true if and only if value is a prime number. */ public static boolean isPrime(int value) { return true ❷; //TODO: Dummy value to be implemented correctly } }
for (int i = 1; i < 20;i++) {
System.out.println(i + " is " + (Prime.isPrime(i) ? " a " : " not a ")
+ " prime number");
}
1 is a prime number 2 is a prime number 3 is a prime number 4 is a prime number 5 is a prime number ...
Input | Expected output | Input | Expected output |
---|---|---|---|
1 |
false |
7 |
true |
2 |
true |
8 |
false |
3 |
true |
9 |
false |
4 |
false |
10 |
false |
5 |
true |
11 |
true |
6 |
false |
12 |
false |
public class PrimeTest { @Test ❶ public void test_1_isNotPrime() { Assert.assertFalse(Prime.isPrime(1)); } @Test ❶ public void test_2_isPrime() { Assert.assertTrue(Prime.isPrime(2)); } void someOrdinaryMethod() ❷ {...} ...
goik@goiki Prime_v01> mvn test ... Running de.hdm_stuttgart.mi.sd1.PrimeTest Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.065 sec <<< FAILURE! ... test_1_isNotPrime(de.hdm_stuttgart.mi.sd1.PrimeTest) Time elapsed: 0.001 sec <<< FAILURE! java.lang.AssertionError at org.junit.Assert.fail(Assert.java:86) at org.junit.Assert.assertTrue(Assert.java:41) at org.junit.Assert.assertFalse(Assert.java:64) at org.junit.Assert.assertFalse(Assert.java:74) ...
@Test public void test_Primes() { Assert.assertTrue(Prime.isPrime(3)); Assert.assertTrue(Prime.isPrime(5)); Assert.assertTrue(Prime.isPrime(7)); Assert.assertTrue(Prime.isPrime(11)); ... } @Test public void testOddNonPrimes() { Assert.assertFalse(Prime.isPrime(9)); Assert.assertFalse(Prime.isPrime(15)); Assert.assertFalse(Prime.isPrime(21));...}
@Test public void testEvenNonPrimes() { for (int i = 2; i < 100; i++) { Assert.assertFalse(Prime.isPrime(2 * i)); } }
public static boolean isPrime(int value) { for (int i = 2; i < value; i++) { if (0 == value % i) { // i divides value return false; } } return value != 1; }
goik@goiki Prime_v01> mvn test
...
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running de.hdm_stuttgart.mi.sd1.PrimeTest
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.055 sec
Results :
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
Try improving the algorithm.
Introducing an error.
101 / 2 = 50 remainder 1 101 / 3 = 33 remainder 2 101 / 4 = 25 remainder 1 101 / 5 = 20 remainder 1 101 / 6 = 16 remainder 5 101 / 7 = 14 remainder 3 101 / 8 = 12 remainder 5 101 / 9 = 11 remainder 2 101 / 10 = 10 remainder 1 101 / 11 = 9 remainder 2 101 / 12 = 8 remainder 5 101 / 13 = 7 remainder 10 ...
Big performance gain:
public static boolean isPrime(int value) {
for (int i = 2; i * i < value; i++) {
if (0 == value % i) {
return false;
}
}
return value != 1;
}
public static boolean isPrime(int value) { //for (int i = 2; i * i < value; i++) { for (int i = 2; i * i <= value; i++) { if (0 == value % i) { return false; } } return value != 1; }
Selected assertion methods.
Considerations when comparing float
and
double
values.
java.lang.AssertionError: Use assertEquals(expected, actual, delta) to compare floating-point numbers at org.junit.Assert.assertEquals(Assert.java:656) at qq.doubleCompareTest.test1_3(doubleCompareTest.java:15) ...
System.out.println("3.6 - 3 * 1.2 == " + (3.6 - 3 * 1.2));
Result:
3.6 - 3 * 1.2 == 4.440892098500626E-16
public class doubleCompareTest {
static final double delta = 1E-15;
/**
* Comparing 3.6 and 3 * 1.2 within delta's limit
*/
@Test
public void test1_3() {
Assert.assertEquals(3.6, 3 * 1.2 , delta);
}
}
public @interface Test { ... } |
|
public class Assert { public static void assertTrue( String message, boolean condition) { ...} public static void assertEquals( long expected, long actual) { ...} ... }
<project ...> ... <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> ... </dependencies> ... </project>
Local: /home/goik/.m2/repository/junit/junit/4.13/junit-4.13.jar
> jar -tf junit-4.13.jar META-INF/ META-INF/MANIFEST.MF org/ org/junit/ ... org/junit/Assert.class ...
Primitive and value types revisited.
|
|
|
|
Array or class instances i.e. String
,
java.util.Scanner
etc.
Value type |
|
a=5 b=1 |
Reference type |
|
r=Joe Simpson s=Joe Simpson |
public static void main(String[] args) { int value = 3; System.out.println( "Before printDuplicateValue: " + value); printDuplicateValue(value); System.out.println( "After printDuplicateValue: " + value); } static void printDuplicateValue(int n) { n = 2 * n; System.out.println( "printDuplicateValue: " + n); } |
Before printDuplicateValue: 3 printDuplicateValue: 6 After printDuplicateValue: 3 |
|
Before duplicateString: My After duplicateString: MyMy |
|
Before duplicateString: My After duplicateString: My |
int a = 1;
int &b = a;
cout << a << " : " << b << endl;
a = 5;
cout << a << " : " << b << endl; |
1 : 1 5 : 5 |
// Passing a reference // to variable n void printDuplicateValue(int& n) { n = 2 * n; cout << "duplicateValue: " << n << endl; } int main() { int value = 3; cout << "Before call: " << value << endl; printDuplicateValue(value); cout << "After call: " << value << endl; } |
Before call: 3 duplicateValue: 6 After call: 6 |
Method calls, behind the scenes.
Stack and heap memory.
Stack frames and value propagation. Using the debugger.
public class Circle { static final double PI = 3.141592653589793; double r; /** Change a circle's area * @param area The desired new area * @return The circle's new radius */ double setArea(final double area ❶) { double val ❷ = area / PI ❸; return ❹ r ❺ = Math.sqrt(val); } } |
|||||
|
|
Class scope (static )
|
Application process |
Instance scope | Object lifetime: new
(...) until being garbage collected.
|
Method scope | Method invocation until return .
|
Allocation of class or array instances:
|
|
De-allocation subject to garbage collection.
One instance per process thread.
Hosting variables (values or references)
enum
)
Modeling finite sets of discrete states.
Examples:
A room's door: {OPEN
, CLOSED
}
State of matter: {SOLID
, LIQUID
,
GASEOUS
}
No dynamic change of state set.
enum
)
Example: Weekdays Monday till Sunday represented by constant
int
values.
Common pitfall examples.
Insufficient means of language protection against self - inflicted problems.
public class Lecture { public final int dayHeld; /* e.g. to be held on Tuesdays */ public final String title; /* e.g. «PHP introduction» */ public Lecture(final int dayHeld, final String title) { this.dayHeld = dayHeld; this.title = title; } }
Quick and dirty:
Class Driver: final Lecture phpIntro = new Lecture(1 /* Monday */, "PHP introduction"), advancedJava = new Lecture(5 /* Friday */, "Advanced Java");
Error prone:
Weeks start on Mondays?
Index starts with 0 or 1?
public class Day { static public final int MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5, SATURDAY = 6, SUNDAY = 7; }
Class Driver: final Lecture phpIntro = new Lecture(Day.MONDAY, "PHP introduction"), advancedJava = new Lecture(Day.FRIDAY, "Advanced Java");
public class Day { ... public static String getDaysName(final int day) { switch (day) { case MONDAY: return "Monday"; case TUESDAY: return "Tuesday"; case WEDNESDAY: return "Wednesday"; case THURSDAY: return "Thursday"; case FRIDAY: return "Friday"; case SATURDAY: return "Saturday"; case SUNDAY: return "Sunday"; default: return "Illegal day's code: " + day; } } }
public class Lecture { public final int dayHeld; ... public String toString() { return "Lecture «" + title + "» being held each " + Day.getDaysName(dayHeld); } }
// Class Driver final Lecture phpIntro = new Lecture( Day.MONDAY, "PHP introduction"), advancedJava = new Lecture( Day.FRIDAY, "Advanced Java"); System.out.println(phpIntro); System.out.println(advancedJava); |
Lecture «PHP introduction» being held each Monday Lecture «Advanced Java» being held each Friday |
// Class Screwed final Lecture phpIntro = new Lecture(88, "PHP introduction"); System.out.println(phpIntro); |
Lecture «PHP introduction» being
held each Illegal day's code: 88 |
/** * Charge double prices on weekends * @param day Day of week * @param amount * @return the effective amount for * given day of week. */ static public int getPrice( final int day, final int amount) { switch (day) { case Day.SATURDAY: case Day.SUNDAY: return 2 * amount; default: return amount; } } |
// Correct System.out.println( getPrice(Day.SUNDAY, 2)); // Argument mismatch System.out.println( getPrice(2, Day.SUNDAY)); 4 7 Bad: No warning message whatsoever! |
enum
)
Representing enumeration values by instances gaining type safety.
Partial problem solution.
Roadmap:
Define a dedicated enumeration representing class.
Create exactly one class instance per enumeration value.
Enumeration value equality comparison by virtue of the
==
operator.
public class Day { static public final Day MONDAY = new Day(), TUESDAY = new Day(), WEDNESDAY = new Day(), THURSDAY = new Day(), FRIDAY = new Day(), SATURDAY = new Day(), SUNDAY = new Day(); }
Note: Class without instance attributes.
Reverting to if .. else if
...
public static String getDaysName(final Day day) { if (MONDAY == day) { // Switch no longer possible, sigh! return "Monday"; } else if (TUESDAY == day) { ... } else if (SUNDAY == day) { return "Sunday"; } else { return "Illegal day instance: " + day; } }
/** * Charge double prices on weekends * @param day Day of week * @param amount * @return the effective amount depending on day of week. */ static public int getPrice(final Day day, final int amount) { if (Day.SATURDAY == day || Day.SUNDAY == day) { return 2 * amount; } else { return amount; } }
Preventing method argument order mismatch:
// Class Driver // o.K. System.out.println(Screwed2.getPrice(Day.SUNDAY, 2)); // Argument mismatch causing compile time type violation error System.out.println(Screwed2.getPrice(2, Day.SUNDAY));
Class Screwed: final Day PAST_SUNDAY = new Day(); final Lecture phpIntro = new Lecture( PAST_SUNDAY, "PHP introduction"); System.out.println(phpIntro.toString()); |
Lecture «PHP introduction» being
held each Illegal day instance:
de.hdm_stuttgart.mi.sd1.
class_wrapper.Day@63961c42 |
enum
)
Clearing the mess.
Sad: switch
still not working.
public class Day { // Disallow object creation outside class private Day() {} static public final Day MONDAY = new Day(), TUESDAY = new Day(), ... SUNDAY = new Day(); }
Class Screwed: Day PAST_SUNDAY = new Day(); Lecture phpIntro = new Lecture( PAST_SUNDAY, "PHP introduction"); System.out.println(phpIntro.toString()); |
Compile time error: 'Day()' has private access in
'de.hdm_stuttgart.mi.sd1.
class_wrapper_private.Day' |
public class Day { public final String name; private Day(final String name) { this.name = name; } static public final Day MONDAY = new Day("Monday"), ... SUNDAY = new Day("Sunday"); public String toString() { return name; } }
enum
)
enum
replacing class
Introducing enum
as kind of restricted
class.
Makes switch
working again!
public enum Day { MONDAY("Monday"), TUESDAY("Tuesday"), ... SUNDAY("Sunday"); final String name; Day(final String name) { this.name = name;} public String toString() { return name;} }
public enum Day { ... public static String getItalianDayName(final Day day) { switch (day) { case MONDAY: return "Lunedì"; case TUESDAY: return "Martedì"; ... case SUNDAY: return "Domenica"; } return null; // Actually unreachable, but static // compiler code analysis is limited } }
public enum Day {
...
private Day(final String name)
{ ... |
Compile time warning: Modifier 'private' is redundant for |
public enum Day {
...
public Day(final String name)
{ ... |
Compile time error: Modifier 'public' not allowed here |
Prohibits enum
external instance creation.
Git:
A completely ignorant, childish person with no manners.
A person who feels justified in their callow behaviour.
A pubescent kid who thinks it's totally cool to act like a moron on the internet, only because no one can actually reach through the screen and punch their lights out.
Creating a git project
Important commands: git add, git commit, git log, ...
git status On branch master ❶ No commits yet ❷ Untracked files: ❸ (use "git add <file>..." to include in what will be committed) Math.java nothing added to commit but untracked files present (use "git add" to track) ❹
public class Math { static public int add( final int a, final int b) { return a + b; } } |
public class Math {
/**
* Summing two int values.
* @param a first value.
* @param b second value.
* @return The sum of both.
*/
static public int add(
final int a, final int b) {
return a + b;
}
} |
> javac Print.java Math.java # Compilation creating Math.class and Print.class
> git status
On branch master
Your branch is up to date with 'origin/master'.
Untracked files:
(use "git add <file>..." to include in what will be committed)
Math.class
Print.class
nothing added to commit but untracked files present (use "git add" to track)
Math.class
and
Print.class
are being generated from
Math.java
and
Print.java
.
Rule of thumb: Do not version dependent objects.
Solution: Add a .gitignore
file to
versioning to contain:
# ignore generated .class files
*.class
git log commit 0137ccd857a242f4751e36bdbce365c6130c3a32 ❶(HEAD -> master) Author: Martin Goik <goik@hdm-stuttgart.de> Date: Sat May 25 11:56:00 2019 +0200 Removing duplicate headline ❷ commit 7f119fac36e02e4c5a7f04f022217b6f744d6e1d ❸ Author: Martin Goik <goik@hdm-stuttgart.de> Date: Sat May 25 11:49:52 2019 +0200 Project Readme.md ❹ ...
git checkout 7f119fac36e02e4c5a7f04f022217b6f744d6e1d Note: checking out '7f119fac36e02e4c5a7f04f022217b6f744d6e1d'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b <new-branch-name> HEAD is now at 7f119fa Project Readme.md
git checkout master Previous HEAD position was 7f119fa Project Readme.md Switched to branch 'master'
Connecting local to remote repository or clone
push local to remote
pull from remote to local
Create empty remote
repository on gitlab.mi.hdm-stuttgart.de
.
Connect local repository to remote
git remote add origin ❶ https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git
origin is an alias for our
remote repository
|
git push --set-upstream origin ❶ master Username for 'https://gitlab.mi.hdm-stuttgart.de': goik ❷ Password for 'https://goik@gitlab.mi.hdm-stuttgart.de': Counting objects: 5, done. Delta compression using up to 6 threads. Compressing objects: 100% (4/4), done. Writing objects: 100% (5/5), 507 bytes | 507.00 KiB/s, done. Total 5 (delta 0), reused 0 (delta 0) To https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git * [new branch] master -> master ❸ Branch 'master' set up to track remote branch 'master' from 'origin'.
> git pull ❶ Username for 'https://gitlab.mi.hdm-stuttgart.de': goik ❷ Password for 'https://goik@gitlab.mi.hdm-stuttgart.de': remote: Enumerating objects: 8, done. remote: Counting objects: 100% (8/8), done. remote: Compressing objects: 100% (6/6), done. remote: Total 6 (delta 1), reused 0 (delta 0) Unpacking objects: 100% (6/6), done. From https://gitlab.mi.hdm-stuttgart.de/goik/gitintro ❸ 733e541..ffff092 master -> origin/master Updating 733e541..ffff092 ❹ Fast-forward Math.java | 10 ++++++++-- ❺ 1 file changed, 8 insertions(+), 2 deletions(-)
Create new possibly non-empty project at https://gitlab.mi.hdm-stuttgart.de.
> git clone https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git Cloning into 'gitintro'... Username for 'https://gitlab.mi.hdm-stuttgart.de': goik Password for 'https://goik@gitlab.mi.hdm-stuttgart.de': remote: Enumerating objects: 5, done. remote: Counting objects: 100% (5/5), done. remote: Compressing objects: 100% (4/4), done. remote: Total 5 (delta 0), reused 0 (delta 0) Unpacking objects: 100% (5/5), done.
Line level conflicts
Manual merge
User A: Print.java | User B: Print.java |
---|---|
// Driver class
public class Print {
public static void
main(String[] args) {
System.out.println
(Math.add(2, 3));
}
} |
/**
* Application entry point
*/
public class Print {
public static void
main(String[] args) {
System.out.println
(Math.add(2, 3));
}
} |
User A | User B |
---|---|
Edit: ... Driver class ... | - |
git commit, git push | - |
- | edit: ... Application entry point ... |
- | git commit |
- | git push: Fail! |
>git push ... To https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git ! [rejected] master -> master (fetch first) error: failed to push some refs to 'https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again.
>git pull ... From https://gitlab.mi.hdm-stuttgart.de/goik/gitintro b003a82..dbbedb0 master -> origin/master Auto-merging Print.java CONFLICT (content): Merge conflict in Print.java Automatic merge failed; fix conflicts and then commit the result.
>git diff Print.java diff --cc Print.java index fc36ae6,7b27edf..0000000 --- a/Print.java +++ b/Print.java @@@ -1,6 -1,4 +1,10 @@@ ++<<<<<<< HEAD +/** ❶ + * Application entry point + */ ++======= + // Driver class ❷ ++>>>>>>> dbbedb0fc29d77beeaaada37f2538d78f82bac93 public class Print { public static void main(String[] args) { System.out.println (Math.add(2, 3)); } }
<<<<<<< HEAD /** * Application entry point */ ======= // Driver class >>>>>>> 10cf21c ... 759462c public class Print { public static void main(String[] args) { System.out.println (Math.add(2, 3)); } } |
➱ | /** * Driver class, application entry point */ public class Print { public static void main(String[] args) { System.out.println (Math.add(2, 3)); } } |
>git add Print.java >git commit --message "Merging changes" [master 173487a] Merging changes >git push ... To https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git 10cf21c..173487a master -> master