Monday 14 March 2011

Summary of Chapter 2: Fundamentals of Object Oriented Programming: Part 2

Object Relationships
The true power of OOP becomes apparent when objects are connected in various relationships. There are many kinds of relationships that are possible. We will consider two of the most fundamental relationships HAS-A and IS-A.

HAS-A
HAS-A refers to the concept of one object contained or owned by another. Members represent the HAS-A relationship. The figure below illustrates the underlying memory model for a HAS-A relationship. Object A contains a reference or a pointer to object B.
                                                                     Has - A Relationship

Object A owns an instance of object B. Coding a HAS-A relationship in SystemVerilog involves instantiating one class inside another or in some other way providing a handle to one class that is stored inside another.
class B; 
endclass
class A; 
   local B b;
   function new(); 
      b = new();
            endfunction 
          endclass
 
class A contains a reference to class B. The constructor for class A, function new(), calls new() on class B to create an instance of it. The member b holds a reference to the newly created instance of B.

IS-A
The IS-A relationship is most often referred to as inheritance. A new class is derived from a previously existing object and inherits its characteristics. Objects created with inheritance are composed using IS-A. The derived object is considered a sub-class or a more specialized version of the parent object.
                                                                       Is A Relationship

To express IS-A using UML, we draw a line between objects with an open arrowhead pointing to the base class. Traditionally, we draw the base class above the derived classes, and the arrows point upward, forming an inheritance tree. SystemVerilog uses the keyword extends to identify an inheritance relationship between classes:
class A;
   int i;
   float f;
endclass
class B extends A;
    string s;
endclass

Class B is derived from A, so it contains all the attributes of A. Any instance of B not only contains the string s, but also the floating point value f and the integer i.