Getter and setter methods

Figure 232. Direct access vs. setter method Slide presentation Create comment in forum
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);}
}

Figure 233. Why adding setter methods? Slide presentation Create comment in forum
  • Allow for change of implementation.

  • Allow for non-business logic concerns. Examples:

    • Logging

    • Adding persistence


Figure 234. Implementation by minutes only Slide presentation Create comment in forum
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);}
}

exercise No. 86

File system representation Create comment in forum

Q:

In Refining access to an employee's attributes you moved the Employee class to a package model.

How are the corresponding Java files Employee.java and Driver.java being represented? What about the generated byte code files Employee.class and Driver.class?

Tip

Use your OS's file system explorer.

A:

Depending on your type of project (Java, Maven,...) both your .java source files and generated .class files will be organized below their respective entry level directories. The following typical layout depends on your Java development environment / IDE:

.java source files

Below folder src.

.class byte code files

Below folder bin.

Packages give rise to further sub directories both for source code and their generated byte code partners. The following example is a minor variation of our employee example. The package model has been transformed into company.model:

Figure 235. Package hierarchy of the employee example Slide presentation Create comment in forum
Package hierarchy of the employee example