OO Programming with Java


Objects & Classes

How to keep track of all the groups that have been created ?

  1. Classes can also have attributes/operations what is represented by static members.
    E.g. System.in and System.out are sample of static members and the mathematical functions from java.lang.Math are mostly static.

The following code gives a sample use of the concept.

public class Group {
  private static Group[] groups = new Group[10];
  private static int     count  = 0;
  
  public static Group create(String name) {
    Group group   = new Group(name);
    groups[count] = group; count++;
    return group;
  }
  
  public static Group   find(String name)    { ... }
  public Group[] groupsWith(Person p) { ... }
  ...

Thus, in the example, instanciation is controlled by the create operation:

Group g1 = Group.create("Dance");
Group g2 = Group.create("Tennis");
...
Group g = Group.find("Dance"); g.addPerson(new Person("Kate"));

As a remark, the preceding principle is well-known in object-oriented engineering and is called the Factory design pattern.


UML/SysML class diagram


2 - 14