OO Programming with Java


Abstraction

  1. Both Person and Group have a name with set/get operations. The code can then be generalized into a new class from which Person/Group will inherit from:
public abstract class NamedElement {
  protected String name;
  public String getName() { return this.name; }
  public void setName(String name) {
    if (name.length() > 1) this.name=name;
    else this.name = "BadName";
  }
  public NamedElement(String name) {
    this.setName(name);
  }
}

Comments:

a. The abstract keyword makes it impossible the instanciation of the class: user has to instanciate a subclass.
b. The protected visibility enable the access of an element in the inheritance hierarchy. Without that, the toString operation from Group can not use the 'name' attribute.


7 - 14