OO Programming with Java


Inheritance

  1. How to define groups with a 'max' capacity ?
    These kind of groups ARE groups with extra attributes/operations. To avoid rewriting the previous code, object-oriented languages invented a particular mechanism called inheritance relation illustrated below:
public class RestrictedGroup extends Group {
  private int capacity = 30;

  public int  getCapacity() { return this.capacity; }
  public void setCapacity(int capacity) { 
    if (capacity > 0) this.capacity = capacity; }
}

So, inheritance is represented by the keyword extends and the parent class, also called the 'superclass', by the keyword super.
As an illustration, the constructor from the current class has now to initialize both capacity and name (what is already done by the Group constructor). So, it can be defined as follow:

public RestrictedGroup(String name, int capacity) {
  super(name); // called the Group constructor
  this.setCapacity(capacity);
 }

UML/SysML class diagram


3 - 14