Overview

  • Objects and Classes

    The concept of classes: Blueprints for objects.

    Example: Rectangles

    UML diagram visualization.

    Lecture notes

Instances of a Class

Instances of a Class

Lecture notes

  • Objects and Classes

Create comment

General class structure

General class structure

Lecture notes

  • Objects and Classes

Create comment

What's a class anyway?

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.

Lecture notes

  • Objects and Classes

Create comment

Rectangle objects

Rectangle objects

Lecture notes

  • Objects and Classes

Create comment

A class describing rectangles

public class Rectangle {
  int width;
  int height;

  // solid or dashed:
  boolean hasSolidBorder;
}
A class describing rectangles

Lecture notes

  • Objects and Classes

Create comment

Rectangle class and instances

layered SVG image

Lecture notes

  • Objects and Classes

Create comment

Rectangle class and instances

layered SVG image

Lecture notes

  • Objects and Classes

Create comment

Rectangle class and instances

layered SVG image

Lecture notes

  • Objects and Classes

Create comment

Rectangle class and instances

layered SVG image

Lecture notes

  • Objects and Classes

Create comment

Generated diagrams

Generated diagrams
Generated diagrams

Lecture notes

  • Objects and Classes

Create comment

Overview

  • Objects and Classes
    • ➟ Working with objects

      Classes and creation of related instances.

      The «new» operator.

      Assignment of attribute values. Working with «null».

      Lecture notes

Creating rectangle instances

Rectangle dashedRectangle = new Rectangle();

Rectangle solidRectangle = new Rectangle();

...

Lecture notes

  • Objects and Classes
    • ➟ Working with objects

Create comment

Syntax creating instances

variable = new (class-name)
Wording example:
  • Create an instance of class Rectangle.

  • Create a Rectangle object.

  • Create a Rectangle.

Lecture notes

  • Objects and Classes
    • ➟ Working with objects

Create comment

Assigning attribute values

Rectangle dashedRectangle = new Rectangle();

dashedRectangle.width = 28;
dashedRectangle.height = 10;
dashedRectangle.hasSolidBorder = false;

Syntax accessing object attributes:

variable.attributeName = value;

Lecture notes

  • Objects and Classes
    • ➟ Working with objects

Create comment

Memory representation

Memory representation

Lecture notes

  • Objects and Classes
    • ➟ Working with objects

Create comment

References and null

Rectangle r = new Rectangle();// Creating an object

r.width = 28; // o.K.

r = null;// removing reference to object

r.width = 28; // Runtime error: NullPointerException (NPE)

Lecture notes

  • Objects and Classes
    • ➟ Working with objects

Create comment

Checking for object presence

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);
}

Lecture notes

  • Objects and Classes
    • ➟ Working with objects

Create comment

Overview

  • Objects and Classes
    • ➟ Packages

      Significance for larger projects.

      Fully qualified vs. «import».

      java.lang and other exceptions.

      Lecture notes

Why packages ?

  • Grouping of related classes (e.g. subsystems).

  • Structuring big systems.

  • Provide access restrictions.

    public, private and protected modifier

  • Resolving class name clashes. Example:

    java.lang.String vs. my.personal.String

Lecture notes

  • Objects and Classes
    • ➟ Packages

Create comment

Rules and conventions

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

Lecture notes

  • Objects and Classes
    • ➟ Packages

Create comment

Qualified name vs. import

Fully qualified class name:
java.util.Scanner  scanner =          // Clumsy and
   new java.util.Scanner (System.in); // redundant
Using import:
import java.util.Scanner; 

public class Q {

  public static void main(String[] args) {
     Scanner  scanner = new Scanner (System.in);
       ...
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Packages

Create comment

Don't be too lazy!

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();
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Packages

Create comment

Classes from package java.lang

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);
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Packages

Create comment

Class, package and file system

Class, package and file system

Lecture notes

  • Objects and Classes
    • ➟ Packages

Create comment

Source hierarchy view

Source hierarchy view
package my.first.javapackage;
        ❷ ❸     ❹
public class Print { 
              ❺
  ...


}

Lecture notes

  • Objects and Classes
    • ➟ Packages

Create comment

Overview

  • Objects and Classes
    • ➟ Object methods

      Object behaviour, state transitions, derived values.

      Selected examples both of state-changing and state-conserving methods.

      Rectangle sample methods.

      Lecture notes

Object methods

Change an object's state.

Example: Scale a rectangle.

Get dependent values

Example: Calculate a rectangle's perimeter.

Combined

Scale a rectangle and calculate its new perimeter.

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Scaling a rectangle

Scaling a rectangle

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Scaling method implementation

public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

    public void scale (int factor) {
        width *= factor;
        height *= factor;
    }
}
Scaling method implementation

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Scaling method signature

void  scale (int factor ) {
...}

No value is being returned to caller.

A single value of type int is being provided as method argument.

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Using scale(...) method

Rectangle r = new Rectangle();
r.width = 33;
r.height = 22;

r.scale(2);

System.out.println("width=" + r.width);
System.out.println("height=" + r.height);
width=66
height=44

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Method definition syntax

public  void  scale (int factor ) { 
   width *= factor; 
   height *= factor;
}
[access modifier]  return_type  methodName  ([arguments] ) {
   [statement(s)] 
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

A rectangle's perimeter

A rectangle's perimeter

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Get perimeter implementation

public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

    public void scale (int factor) { ... }

    public int getPerimeter() {
        return 2 * (width + height);
    }
}
Get perimeter implementation

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Using Rectangle.getPerimeter()

Rectangle r = new Rectangle();

r.width = 33;
r.height = 22;

System.out.println("Perimeter=" + r.getPerimeter());
Perimeter=110

Lecture notes

  • Objects and Classes
    • ➟ Object methods

Create comment

Overview

  • Objects and Classes
    • ➟ Object methods
      • ➟ Encapsulation and access control

        Justifying access restrictions.

        public, protected «package local» and private.

        Best practices.

        Lecture notes

Access control: Overall objectives

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Encapsulation and access control

Create comment

Example: Implementing time and date

public class Time {
  private long  secondsSince_2000_01_01;

  public int getSecond() { 
    return
    (int) secondsSince_2000_01_01 % (60);
  }
  public int getMinute() {
    return (int)
      (secondsSince_2000_01_01 / 60) % 60;
  }
  // ...
}
public class Time {
  private int second, minute,
         hour,day, month, year;

  public int getSecond() { 
        return second;
  }
  public int getMinute() { 
        return minute;
  }
    // ...
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Encapsulation and access control

Create comment

Access violation

public class Q {
  public static void main(String[] args) {

      Time t = new Time();

      // Error: 'secondsSince_2000_01_01' has private access in 'Time'
      t.secondsSince_2000_01_01 = 33445354L;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Encapsulation and access control

Create comment

Access rules

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

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Encapsulation and access control

Create comment

Tips on Choosing an Access Level

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

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Encapsulation and access control

Create comment

Followup exercises

Overview

  • Objects and Classes
    • ➟ Object methods
      • ➟ Getter and setter methods

        Lecture notes

Direct access vs. setter method

package hour_second.direct;

public class Time {
    public int hour, minute;
}
package hour_second;
import hour_second.direct.Time;

public class DirectAccess {
    Time time = new Time();
    void init() {
        time.hour = 17;
        time.minute = 45;
    }
}
package hour_second.setter;

public class Time {
    private int hour, minute;
    public void setTime(int h, int m) {
        minute = m;
        hour = h;
    }
}
package hour_second;
import hour_second.setter.Time;
public class SetterAccess {
    Time time = new Time();
    void init() { time.setTime(17, 45);}
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Getter and setter methods

Create comment

Why adding setter methods?

  • Allow for change of implementation.

  • Allow for non-business logic concerns. Examples:

    • Logging

    • Adding persistence

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Getter and setter methods

Create comment

Implementation by minutes only

package only_minute.direct;
public class Time {
  // Minutes since 00:00
  public int minute;
}
package only_minute;
import only_minute.direct.Time;
public class DirectAccess {
  Time time = new Time();
  void init() {
    time.minute = 1065;// 17:45
  }
}
package only_minute.setter;
public class Time {
  private int minute;
  public void setTime(int h, int m) {
    minute = m + 60 * h;
  }
}
package only_minute;
import only_minute.setter.Time;
public class SetterAccess {
    Time time = new Time();
    void init() { time.setTime(0, 0);}
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Getter and setter methods

Create comment

Overview

  • Objects and Classes
    • ➟ Object methods
      • ➟ Signatures

        Type signatures.

        Method signatures: Prerequisite understanding method overloading.

        Lecture notes

Defining type signatures

boolean  startsWith​(String prefix, int toffset)  

Return type boolean

Arguments among with their respective types and order:

  1. Type String

  2. Type int

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Signatures

Create comment

Type signature examples

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)

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Signatures

Create comment

Defining method signatures

boolean startsWith(String prefix, int toffset)  

Method name startsWith.

Number of arguments among with their respective types and order.

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Signatures

Create comment

Method signature examples

Method Method name Method signature
void print() 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) print (int, float)
void display(float a, int b) display (float, int)

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Signatures

Create comment

Followup exercise

No. 85: Method signature variants

Overview

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

        Same name, different argument types.

        «C» programming language comparison.

        Common examples.

        Lecture notes

Method overloading: Same name, different signature

public class Print {
  public void print() {             // (void)
    System.out.println("No argument");
  }
  public void print(int i) {        // (int)
    System.out.println("int value " + i);
  }
  public void print(double d) {     // (double)
    System.out.println("double value " + d);
  }
  public void print(int i, int j) { // (int, int)
      System.out.println("Two int values "+
         i + " and " + j);
  }
}
Print p = new Print();
p.print();
p.print(33);
p.print(4.333);
p.print(-1, 7);
No argument
int value 33
double value 4.333
Two int values -1 and 7

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

Create comment

Overloading, alternate names

  • Static polymorphism.

  • Compile time binding.

  • Early binding.

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

Create comment

No such concept in C

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);
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

Create comment

What about return type?

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.

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

Create comment

Method signatures rationale

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)

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

Create comment

Method signatures rationale

Method signatures rationale

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

Create comment

Followup exercise

No. 86: Will a match be found?

Example: System.out.print(...)

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Method overloading

Create comment

Overview

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

        Combined instance creation and initialization.

        Constructors are methods, but ...

        Constructor overloading and a class' default constructor.

        Lecture notes

Creating and initializing rectangles

int a;
a = 33;
Rectangle r = new Rectangle();

r.width = 28;
r.height = 10;
r.hasSolidBorder = false;

Combining statements desired:

int a = 33; // works!
Rectangle r = new Rectangle(28, 10, false);//how ???

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Defining a constructor

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;
    }
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Constructor syntax

constructorName (listOfArguments) {
    [constructor body]
}
Empty argument list

Default constructor e.g. obj = new MyClass().

Non-empty argument list

Non-default constructor, e.g. obj = new MyClass("xyz").

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Constructors

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

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Multiple constructors by overloading

public class Rectangle {
    int width, height;

    public Rectangle() {
        width = height = 1;
    }
    public Rectangle(int width, int height){
        this.width = width;
        this.height = height;
    }
    public Rectangle(int widthAndHeight) {
        width = height = widthAndHeight;
    }
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Constructor calls within constructor

public class Rectangle {
  int width, height;

  public Rectangle(int width,
                int height){
    this.width = width;
    this.height = height;
  }
  public Rectangle() {
    width = height = 1;
  }
  public Rectangle(
     int widthAndHeight) {
    width = height =
          widthAndHeight;
  }
}
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); 
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Instances by overloaded constructors

Rectangle standard = new Rectangle(); // 1 x 1
Rectangle square = new Rectangle(2); // 2 x 2
Rectangle individual = new Rectangle(2, 7); // 2 x 7
Instances by overloaded constructors

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

No constructor vs. default constructor

Equivalent: Rectangle r = new Rectangle();
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

    // Default constructor, empty body.
    public Rectangle ( ){}
}
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Absent default constructor

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;
  }
}
// o.K.: Using non-default
// constructor.

Rectangle r = 
   new Rectangle(3, 6, false);
// Wrong: Default constructor
// undefined, but non-default
// constructor present.

Rectangle r = new Rectangle();

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Constructors

Create comment

Followup exercises

Overview

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

        Class, method and block scopes.

        Documentation, «good» variable names and the this keyword.

        Lecture notes

Circle and variable scopes

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Circle and variable scopes

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Circle and variable scopes

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Documenting classes and methods

/** 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;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Generated Javadoc

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Generated Javadoc

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Generated Javadoc

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Generated Javadoc

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Generated Javadoc

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Refactoring «r» ⇒ «radius»

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Refactoring «r» ⇒ «radius»

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Refactoring «r» ⇒ «radius»

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Scope assignment problem

/** 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;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

this overriding method scope

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

this overriding method scope

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

this overriding method scope

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

this overriding method scope

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

this overriding method scope

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Object methods
      • ➟ Scopes

Create comment

Followup exercise

No. 95: Turning seconds into weeks part 2

Overview

  • Objects and Classes
    • ➟ Class members and methods

      Motivating class attributes and methods.

      Example: A club affiliating members.

      Syntax of static and employment considerations

      Lecture notes

Club membership objectives

  • 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 instances receive current member count.

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Implementing club members.

public class ClubMember {

  final private String name;

  public ClubMember(final String name) {
    this.name = name;
  }
  public String getDetails() {
    return "Member " + name;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Showing membership info.

final ClubMember
   john = new ClubMember("John"),
  karen = new ClubMember("Karen");

System.out.println(john.getDetails());
System.out.println(karen.getDetails());
Member John
Member Karen

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Implementing membership numbers.

emphapublic 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 getDetails() {
    return "Member " + name + ", member number " + memberNumber ;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Showing membership numbers.

final ClubMember
   john = new ClubMember("John"),
  karen = new ClubMember("Karen");

System.out.println(john.getDetails());
System.out.println(karen.getDetails());
Member John, member number 1
Member Karen, member number 2

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Accessing the club's overall member count?

public class ClubMember {

  static private int memberCount = 0;
  ...
  public ClubMember(final String name) {
    this.name = name;
    memberNumber = ++memberCount;
  }
  static public int getMemberCount()  {
    return memberCount; 
  }
  ...
}

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Accessing the club's member count

final ClubMember
   john = new ClubMember("John"),
  karen = new ClubMember("Karen"),
  petra = new ClubMember("Petra");

System.out.println(karen.getDetails());

System.out.println("Club's member count:"
   + ClubMember.getMemberCount());
// Good: Prevent tampering memberCount
// variable.
Member Karen, member number 2
Club's member count:3

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Do we really require an instance?

public class Helper {

  public int maximum(int a, int b) {
    if (a < b) {
      return b;
    } else {
      return a;
    }
  }
}
final Helper help = new Helper();

System.out.println("Maximum: " +
            help.maximum(-3, 5));
Maximum: 5

Observation: Instance state irrelevant.

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Favour class method over instance method

public class Helper {

  static public int
     maximum(int a, int b) {
    if (a < b) {
      return b;
    } else {
      return a;
    }
  }
}
System.out.println("Maximum: " +
     Helper.maximum(-3, 5));
Maximum: 5

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Syntax accessing class members

Class Variable

{class name}.{variableName}

Class Method

{class name}.{methodName}([parameter])

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

static / non-static wrap up

public class X {
  int a; 
  static int b; 

Variable a defined once per instance of class X.

Variable b defined once per class X.

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods

Create comment

Followup exercises

Overview

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

        Cross project dependencies.

        Repositories and project artifacts.

        Lecture notes

Newton's letter to Robert Hooke

Newton's letter to Robert Hooke

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

Project «lottery» depending on «helper»

Project «lottery» depending on «helper»

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

Providing project «helper»

Helper.java pom.xml
package
de.hdm_stuttgart.de.mi.sd1;
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...>
 <modelVersion>4.0.0</modelVersion>

 <groupId>de.hdm_stuttgart.de.mi.sd1</groupId>
 <artifactId>helper</artifactId>
 <version>0.9</version>
 <packaging>jar</packaging>
 <name>helper</name>
...
</project>

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

Install project «Helper»

goik@goiki Helper> mvn install
[INFO] Scanning for projects...
[INFO] -------------------------------------------
[INFO] Building helper 0.9
..
--------------------------------------------------
 T E S T S
--------------------------------------------------
Running de.hdm_stuttgart.de.mi.sd1.HelperTest
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0,
...
[INFO] Installing .../Helper/target/helper-0.9.jar to
  /ma/goik/.m2/repository/de/hdm_stuttgart/de/mi/sd1/helper/0.9/helper-0.9.jar

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

helper-0.9.jar archive content

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/de/
   creating: de/hdm_stuttgart/de/mi/
   creating: de/hdm_stuttgart/de/mi/sd1/
  inflating: de/hdm_stuttgart/de/mi/sd1/Helper.class
   creating: META-INF/maven/
   creating: META-INF/maven/de.hdm_stuttgart.de.mi.sd1/
   creating: META-INF/maven/de.hdm_stuttgart.de.mi.sd1/helper/
  inflating: META-INF/maven/de.hdm_stuttgart.de.mi.sd1/helper/pom.xml
  inflating: META-INF/maven/de.hdm_stuttgart.de.mi.sd1/helper/pom.properties

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

Consuming project «Lottery»

<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
  ...
  <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.de.mi.sd1</groupId>
      <artifactId>helper</artifactId>
      <version>0.9</version>
    </dependency>
...
</project>

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

External libraries view

External libraries view

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

Using Helper.factorial(...)

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");
}

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

Maven repositories

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Project dependencies and Maven

Create comment

Followup exercise

No. 106: Dealing with local Maven dependencies

Overview

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Cancelling fractions

        Lecture notes

Defining a dependency to another Maven artifact.

Defining a dependency to another Maven artifact.

Lecture notes

  • Objects and Classes
    • ➟ Class members and methods
      • ➟ Cancelling fractions

Create comment

Followup exercises

Overview

  • Objects and Classes
    • ➟ Value types and reference types

      Primitive and value types revisited.

      Lecture notes

Value vs. reference type variables

Value type: Holding data within own memory location
  • byte

  • short

  • int

  • long

  • float

  • double

  • char

  • boolean

Reference type: Holding a reference to an object

All class instances i.e. String, java.util.Scanner etc.

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Different behaviour!

Value type
int a = 1;
int b = a;
a = 5;
System.out.println("a=" + a);
System.out.println("b=" + b);
a=5
b=1
Reference type
StringBuffer r = new StringBuffer("Joe");
StringBuffer s = r;
r.append(" Simpson");
System.out.println("r=" + r);
System.out.println("s=" + s);
r=Joe Simpson
s=Joe Simpson

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Value variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Value variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Value variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Value variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Reference variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Reference variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Reference variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Reference variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Reference variable Details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Only «call-by-value» in Java

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

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-value» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-value» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-value» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-value» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-value» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-value» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-reference» for objects?

public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("My");
  System.out.println("Before duplicateString: "
    + buffer);
  duplicateString(buffer);
  System.out.println("After duplicateString: "
    + buffer);
}
static void duplicateString(StringBuffer b) {
    b.append(b); // Append self
}
Before duplicateString: My
After duplicateString: MyMy  

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

«call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» in Java!

public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("My");
  System.out.println("Before duplicateString: "
    + buffer);
  replaceString(buffer);
  System.out.println("After duplicateString: "
    + buffer);
}
static void replaceString(StringBuffer b) {
  b = new StringBuffer("Replacement");
}
Before duplicateString: My
After duplicateString: My

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

No «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

C++ offers true «call-by-reference»

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

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

C++ «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

C++ «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

C++ «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

C++ «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

C++ «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

C++ «call-by-reference» details

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Value types and reference types

Create comment

Overview

  • Objects and Classes
    • ➟ Method calls, the details

      Method calls, behind the scenes.

      Stack and heap memory.

      Stack frames and value propagation. Using the debugger.

      Lecture notes

Method calling

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);
  }
}

Passing arguments.

Defining method local variables.

Accessing class variable.

returning values.

Accessing instance variable.

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Three variable scopes

public class Circle {

  static final double
    PI  = 3.141592653589793;

  double r  ;

  double setArea(final double area ) {
    double val  ...
    ...
  }
}

Class scope.

Instance scope

Method scope

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Scope lifetimes

Class scope (static) Application process
Instance scope Object lifetime: new (...) until being garbage collected.
Method scope During method call until return.

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Two runtime memory categories

Heap memory
  • Allocation by new Classname ().

  • De-allocation subject to garbage collection.

Execution stack
  • One instance per process thread.

  • Hosting variables (values or references)

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Stack: Four operations

Method Description Precondition Access type
push(...)

Add object on top

-

Modify

pop()

Read + remove topmost object

Stack not empty

Modify

top()

Read topmost object

Stack not empty

Read only

empty()

true if and only if stack is empty

-

Read only

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Example: Storing integer values

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Example: Storing integer values

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Example: Storing integer values

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Example: Storing integer values

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Example: Storing integer values

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Example: Storing integer values

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Example: Storing integer values

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Method calling

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Call stack trace

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

IDE debugger

IDE debugger

Lecture notes

  • Objects and Classes
    • ➟ Method calls, the details

Create comment

Overview

  • Objects and Classes
    • ➟ Enumerations (enum).

      Lecture notes

Motivation

  • Modeling finite sets of discrete states.

  • No dynamic change of state set.

  • Examples:

    Door: {OPEN, CLOSED}

    State of matter: {SOLID, LIQUID, GASEOUS}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).

Create comment

Overview

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

        Example: Weekdays Monday till Sunday represented by constant int values.

        Common pitfall examples.

        Insufficient means of language protection against self - inflicted problems.

        Lecture notes

Weekdays int representation

public class Day {

  static public final int
    MONDAY    = 1,
    TUESDAY   = 2,
    WEDNESDAY = 3,
    THURSDAY  = 4,
    FRIDAY    = 5,
    SATURDAY  = 6,
    SUNDAY    = 7;
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Weekly offered lectures

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;
    }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Weekly offered lectures

Class Driver:

final Lecture
  phpIntro     = new Lecture(Day.MONDAY, "PHP introduction"),
  advancedJava = new Lecture(Day.FRIDAY, "Advanced Java");

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Integer values to day names

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;
    }
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Providing lecture info

public class Lecture {
...
  public String toString() {
    return "Lecture «" + title + "» being held each " +
           Day.getDaysName(dayHeld);
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Printing lecture info

public class Lecture {
...
  public String toString() {
    return "Lecture «" + title + "» being held each " + Day.getDaysName(dayHeld);
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Sample lectures

// 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

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Bogus enumeration value

// 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

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Argument order mismatch

/**
* 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(Screwed2.
   getPrice(Day.SUNDAY,  2));

// Argument mismatch
System.out.println(Screwed2.
   getPrice(2, Day.SUNDAY));
4
7

No warning message whatsoever!

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by integer representation

Create comment

Overview

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by dedicated class

        Representing enumeration values by instances gaining type safety.

        Partial problem solution.

        Lecture notes

Enumeration by instances

Roadmap:

  • Define a dedicated class representing the enumeration.

  • Create exactly one instance per enumeration value.

  • Enumeration value equality comparison by virtue of the == operator.

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by dedicated class

Create comment

Class instance per enumeration value

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();
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by dedicated class

Create comment

switch no longer works!

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;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by dedicated class

Create comment

Re-writing getPrice()

/**
 * 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;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by dedicated class

Create comment

Argument mismatch error

// Class Driver

// o.K.
System.out.println(Screwed2.getPrice(Day.SUNDAY,  2));

// Argument mismatch causing type violation error
System.out.println(Screwed2.getPrice(2, Day.SUNDAY));

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by dedicated class

Create comment

Creating an undesired instance

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

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Enumeration by dedicated class

Create comment

Overview

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Defining a private constructor

        Clearing the mess.

        switch still does not work.

        Lecture notes

Define a private Day constructor

public class Day {

  // Disallow object creation outside class
  private Day() {} 

  static public final Day
    MONDAY    = new Day(),
    TUESDAY   = new Day(),
  ...
    SUNDAY    = new Day();
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Defining a private constructor

Create comment

Preventing undesired Day instance creation

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'

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Defining a private constructor

Create comment

Even better: Adding day name attribute

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; }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ Defining a private constructor

Create comment

Overview

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ enum replacing class

        Introducing enum as kind of restricted class.

        switch working again!

        Lecture notes

enum Day

public enum Day {

  MONDAY("Monday"),
  TUESDAY("Tuesday"),
  ...
  SUNDAY("Sunday");

  final String name;
  Day(final String name) { this.name = name;}

  public String toString() { return name;}
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ enum replacing class

Create comment

switch statements working again

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
                 // code analysis is limited
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ enum replacing class

Create comment

Constructor implicitly private

public enum Day {
  ...
  private Day(final String name)
    { ...

Compile time warning:

Modifier 'private' is redundant for enum constructors

public enum Day {
  ...
  public Day(final String name)
    { ...

Compile time error:

Modifier 'public' not allowed here

Prohibits enum external instance creation.

Lecture notes

  • Objects and Classes
    • ➟ Enumerations (enum).
      • ➟ enum replacing class

Create comment

Followup exercises

Overview

  • Objects and Classes
    • ➟ Unit testing

      Test categories.

      Why unit testing? Idea of test «driven development».

      Required steps.

      Lecture notes

Recommended reading

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Test categories

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

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Example: Computing prime numbers

Informal problem specification:

A prime number is a whole number greater than 1 whose only factors are 1 and itself.

Examples: 2, 3, 5, 7, 11, 13, 17, 23, ...

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Unit test principle

layered SVG image

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Test driven development

First write tests, then implement.

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Steps in Unit Testing

  1. Specify but not yet implement classes / methods.

  2. Write skeleton (dummy) implementations.

  3. Write corresponding unit tests.

  4. Implement skeleton.

  5. Test your implementation.

Lecture notes

  • Objects and Classes
    • ➟ Unit testing

Create comment

Overview

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

        Providing both an implementation and related tests possibly revealing coding flaws.

        Providing prime number related tests.

        Lecture notes

Step 1 + 2: Specify method, write skeleton

/**
 * 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 
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Execution yet being flawed

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

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Sample test data

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

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Step 3: Junit based specification test

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()  {...}
...

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Junit skeleton test result (Maven CLI)

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

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Junit skeleton test result (IDE)

Junit skeleton test result (IDE)

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Step 3: Providing more prime tests

@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));...}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Step 3: Prime mass testing

@Test public void testEvenNonPrimes() {
  for (int i = 2; i < 100; i++) {
    Assert.assertFalse(Prime.isPrime(2 * i));
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Step 4: Implement skeleton

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;
}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Step 5: Testing our first implementation

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

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Tests and implementation

Create comment

Overview

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Improving the algorithm

        Try improving the algorithm.

        Introducing an error.

        Lecture notes

Implementation observation

101 / 2  = 50.5
101 / 3  = 33.6...
101 / 4  = 25.25
101 / 5  = 20.20
101 / 6  = 16.83...
101 / 7  = 14.43...
101 / 8  = 12.625
101 / 9  = 11.2...
101 / 10  = 10.1
101 / 11  = 9.18...
101 / 12  = 8.4...
101 / 13  = 7.7...
...

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Improving the algorithm

Create comment

Changing the implementation

public static boolean isPrime(int value) {
  for (int i = 2; i * i < value; i++) {
    if (0 == value % i) {
      return false;
    }
  }
  return value != 1;
}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Improving the algorithm

Create comment

Regression test

Regression test

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Improving the algorithm

Create comment

Correcting the implementation

public static boolean isPrime(int value) {
  for (int i = 2; i * i <= value; i++) {
    if (0 == value % i) {
      return false;
    }
  }
  return value != 1;
}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Improving the algorithm

Create comment

Repeating regression test

Repeating regression test

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Improving the algorithm

Create comment

Overview

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Helpful methods

        Selected assertion methods.

        Considerations when comparing float and double values.

        Lecture notes

Available comparison methods

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Helpful methods

Create comment

Caution comparing float / double !!

Caution comparing float / double !!

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Helpful methods

Create comment

Weird arithmetics?

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

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Helpful methods

Create comment

Limited representation precision

System.out.println("3.6 - 3 * 1.2 == " + (3.6 - 3 * 1.2));

Result:

3.6 - 3 * 1.2 == 4.440892098500626E-16

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Helpful methods

Create comment

Solving the issue

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);
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Helpful methods

Create comment

Followup exercises

Overview

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Technical details

        Junit Building Blocks: Classes and interfaces

        Integration using Maven.

        Lecture notes

The @Test annotation

public
@interface Test {
...
}
  • @interface defining an annotation.

  • Purpose: Allows for automatic detection of test methods.

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Technical details

Create comment

The Assert class

public class Assert {

  public static void assertTrue(
    String message, boolean condition) { ...}

  public static void assertEquals(
    long expected, long actual) { ...}
...
}

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Technical details

Create comment

Importing dependencies

<project ...>
...
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>

      <scope>test</scope>
    </dependency>
    ...
  </dependencies>
  ...
</project>

Local file path:

/home/goik/.m2/repository/junit/junit/4.12/junit-4.12.jar

Remote address:

https://mvnrepository.com/artifact/junit/junit/4.12

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Technical details

Create comment

Dependency archive content

> jar -tf junit-4.12.jar
META-INF/
META-INF/MANIFEST.MF
org/
org/junit/
...
org/junit/Assert.class
...

Lecture notes

  • Objects and Classes
    • ➟ Unit testing
      • ➟ Technical details

Create comment

Overview

  • Objects and Classes
    • ➟ Using git

      Lecture notes

Useful links

Lecture notes

  • Objects and Classes
    • ➟ Using git

Create comment

Overview

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

        Creating a git project

        Important commands: git add, git commit, git log, ...

        Lecture notes

Initialize git project

  • git init

  • Result: Sub folder .git containing project's metadata and versioning history

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Configure author related data.

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Adding resources to project index and staging area

  • git add Math.java

  • Result: New files will show up upon invocation of git status.

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Committing change set

  • git commit --message "New math class containing single method"

  • Result: Commit change set to repository adding given message to project log.

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Project versioning status

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) 

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Adding a comment

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;
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

git diff tracing changes

git diff tracing changes

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Reverting individual file.

>git checkout --  Math.java 

>git diff Math.java 
>

Double dashes '--' disambiguating branch names from file names.

Replace working tree file Math.java by repository master.

No difference working tree to master branch.

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Compiling, Math.class and Print.class.

> 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)

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Math.class, Print.class and versioning.

  1. Math.class and Print.class are being generated from Math.java and Print.java.

  2. Rule of thumb: Do not version dependent objects.

Solution: Add a .gitignore file to versioning to contain:

# ignore generated .class files
*.class

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Show project's log

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

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Switch to an older revision ...

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

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

... and forth to current master's HEAD

git checkout master
Previous HEAD position was 7f119fa Project Readme.md
Switched to branch 'master'

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Working with git locally.

Create comment

Followup exercise

No. 120: git local, DIY

Overview

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

        Connecting local to remote repository or clone

        push local to remote

        pull from remote to local

        Lecture notes

Centralized remote repository

See multi+remote/shared git:

  1. Create empty remote repository on gitlab.mi.hdm-stuttgart.de.

  2. Connect local repository to remote

  3. push or pull content

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

Create comment

Step 1: Create remote repository

Step 1: Create remote repository

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

Create comment

Step 2: Retrieve remote repository address

Step 2: Retrieve remote repository address

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

Create comment

Step 2: Connect to remote repository

git remote add origin  https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git

The term origin refers to the remote repository working as an alias for https://gitlab.mi.hdm-stuttgart.de/goik/gitintro.git.

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

Create comment

Step 3: Push local to remote

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

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

Create comment

Step 3: Pull from remote to local

> 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(-)

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

Create comment

Alternative: Create remote + clone

  1. Create new possibly non-empty project at https://gitlab.mi.hdm-stuttgart.de.

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

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Shared development with centralized remote.

Create comment

Overview

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

        Line level conflicts

        Manual merge

        Lecture notes

Conflicting changes

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));
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

Commit schedule

User A User B
Edit: ... Driver class ... -
git commit, git push -
- edit: ... Application entry point ...
- git commit
- git push: Fail!

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

User B: git push fails

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

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

User B: git pull fails as well

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

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

Merge conflict details

>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));
  }
}

Changes of user A.

Own changes of user B.

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

Struggling for resolution

Struggling for resolution

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

Merging Print.java manually

<<<<<<< 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));
  }
}

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

Commit and push merge

>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

Lecture notes

  • Objects and Classes
    • ➟ Using git
      • ➟ Conflicts

Create comment

Followup exercise

No. 121: git distributed, DIY