3.11. Overriding the Virtual Object Methods

The second issue in the design of a derived class revolves around the three virtual methods that every class implicitly inherits from Object. Recall that by default, ToString() prints out the name of the class. It is generally more useful for a class to display a representation of its internal state. For example, here is the ToString() implementation of our OrQuery class (the lparen and rparen members keep track of any parentheses associated with the query):

override public string ToString()
{
    StringBuilder sb = new StringBuilder( 8 );

    if ( m_lparen != 0 )
         gen_lparen( ref sb, m_lparen );
    sb.Append( m_lop.ToString() );
    sb.Append( " || " );
    sb.Append( m_rop.ToString() );

    if ( m_rparen != 0 )
         gen_rparen( ref sb, m_rparen );

    return sb.ToString();
}

ToString() is intended primarily as a debugging aid, although no constraint is imposed on how we might choose to use it. However, many users may be reluctant to invoke ToString() for display purposes other than debugging. For that reason you may consider providing a Display() or Print() function as well.

Why do I use the StringBuilder class object rather than directly building up a string? Purely for efficiency. A string object is immutable. Each string modification results in the generation of a new string object. For example, to build up the following OrQuery representation directly in a string object:

(( alice && emma ) || weeks )

results in the generation of nine temporary string objects—one with the insertion of each new element. StringBuilder is mutable. It allows us to build up a string representation without generating multiple instances. After we have completed modifying our string, we extract it from the StringBuilder object using its ToString() member function.

By default, Equals() implements reference equality; that is, it returns true only if the two objects being compared are actually the same object. In general, when we implement a class, we'll want to override Equals() so that it represents value equality—that is, so that it returns true when two independent class objects contain the same values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.233