Class/Object Relationships

We will discuss and use 5 basic relationships between classes (and therefore objects) and attributes:

  1. Encapsulation - class/attribute relationship
    • The data (attributes), methods (behaviors), and all functionality related to concept the class represents is coded inside the class.
    • Data hiding enforces this - data is private, meaning it can only be accessed through methods written by the class designer.
    • The methods define the interface between the program using the class and the object's data.
    • Rules about the class behavior and how the data relates (often called the invariant of the class) cannot be bypassed by the calling function.
    • In Java, data hiding is done with access control; instance variables should be declared as private.

  2. Composition - class/class relationship, can be strong or weak association
    • A class is composed of attributes, which can be primitives, but are often of other classes.
    • The relationship between these classes is called composition.
    • Note: sometimes this is called containment, but be careful, that term has a specific and different meaning in many contexts, including Java, where it usually means a Container Class.

  3. Association - class/attribute relationship
    • strong: "hasa", attribute, instance variable, fully encapsulated in the class, life of attribute = life of the object, life of the association = life of the object
    • weak: not really an attribute; the association is temporary. It could be passed as an argument, or have reference, be a reference in a container (like an array); the object has its own life beyond the use of the reference.

  4. Inheritance - "isa", class/class relationship
    • A new class can be created from an existing class.
    • The new class inherits the attributes and behaviors (instance variables and methods) for the existing class.
    • Classes related by inheritance are called parent/child classes or base/derived classes or super-/sub-classes.
    • A set of classes related by inheritance is called a class hierarchy.

  5. Polymorphism - class/class relationship

    There are 3 basic conditions for polymorphism:
    1. have a hierarchy
    2. have a parent reference that refers to an object of the child
    3. child class overrides a method in the parent

    When the method is called with the parent reference, it figures out which exact method to call (uses dynamic or late binding).

  6. We'll talk about this more as it is a fundamental concept of OO and you will be using it extensively in your projects.