Home > Articles > Software Development & Management > Object Technology

This chapter is from the book

This chapter is from the book

Object-Oriented Features

As an object-oriented language, C# supports inheritance, encapsulation, and polymorphism. Conceptually, the capabilities of C# are the same as other object-oriented languages, but the syntax and semantics differ in subtle ways that developers must be aware of. A discussion of basic object-oriented concepts is outside the scope of this book, but the following sections detail the primary ways C# supports the object-oriented principles of inheritance, encapsulation, and polymorphism.

Inheritance

Inheritance in a C# class is specified in the class declaration. A C# class may inherit from only a single base class. However, a class may inherit multiple interfaces, as will be explained in the next chapter in the section on interfaces. Listing 3.5 shows how to declare an inheritance relationship between classes.

Listing 3.5 Declaring Inheritance (Inheritance.cs)

using System;

public class BaseClass
{
  public double myDouble = 9.3d;
}

public class DerivedClass : BaseClass
{
}

class Inheritance
{
  static void Main()
  {
   DerivedClass myDerived = new DerivedClass();

   Console.WriteLine("myDerived.myDouble = {0}", 
     myDerived.myDouble);
   Console.ReadLine();
  }
}

Listing 3.5 demonstrates how a derived class inherits from its base class. Although myDouble doesn't physically reside in DerivedClass, it is still a member of DerivedClass by virtue of inheritance. This is why myDouble can be accessed through an instance of DerivedClass in the Main method.

Hiding

A derived type can hide members of its base type, making the base type member invisible without an explicit reference to the base type member. Hidden members must be decorated with the new modifier; otherwise, the C# compiler will issue a warning.

Warnings for the new modifier are by design, and there are a couple of good reasons for this. Because part of the C# philosophy is for the code to be explicit in what it does, warnings on the new modifier make the developers think twice about what they are doing.

Viewing Compiler Messages

To see compiler warnings, choose Tools, Options and check Show Command Line in the Compiling and Running group box. Press Shift+F9 to build the program, and the Messages window will appear at the bottom of the screen with a Build tab that will display warnings, if any. Click the pin glyph on the right of the window to get it to slide down and out of the way while you're working.

More importantly, the new modifier prevents versioning problems that occur when a third-party component is updated. If that third-party component introduces a member with the same identifier as a local derived type, the condition will be caught by the compiler warning. Code written in other languages with implicit polymorphism would break under these conditions. C# support of polymorphism is described in the section "Polymorphism." Listing 3.6 shows how to hide base type members.

Listing 3.6 Hiding Base Type Members (Hiding.cs)

using System;

public class BaseClass
{
  public double myDouble = 9.3d;
}

public class DerivedClass : BaseClass
{
  public new double myDouble = 5.7d;
}

class Hiding
{
  static void Main()
  {
   DerivedClass myDerived = new DerivedClass();

   Console.WriteLine("myDerived.myDouble = {0}", 
     myDerived.myDouble);
   Console.ReadLine();
  }
}

By physically declaring myDouble, DerivedClass hides access to myDouble in BaseClass. Therefore, referencing myDouble through an instance of DerivedClass will return a result of the myDouble in DerivedClass only. This behavior applies to other type members also, such as methods, making code more robust by avoiding implicit polymorphism.

Abstract Classes

Abstract classes provide both implementation and interface to derived classes. Because they are abstract, they cannot be instantiated. The primary difference between abstract classes and interfaces is that abstract classes may define implementation, whereas interfaces may not. Listing 3.7 shows how to define and use an abstract class.

Listing 3.7 Defining and Using an Abstract Class (AbstractClass.cs)

using System;

public abstract class BaseClass
{
  public abstract void AbstractMethod();

  public virtual void ImplementedMethod()
  {
   Console.WriteLine("Implemented Method.");
  }
}

public class DerivedClass : BaseClass
{
  public override void AbstractMethod()
  {
   Console.WriteLine("Abstract Method.");
  }
}

class AbstractClass
{
  static void Main()
 {
    DerivedClass myDerived = new DerivedClass();

   myDerived.ImplementedMethod();
   myDerived.AbstractMethod();

   Console.ReadLine();
  }
}

Abstract methods, as shown in BaseClass of Listing 3.7, are decorated with the abstract modifier and don't have an implementation. The C# compiler forces derived classes to implement all abstract members of an abstract class. The DerivedClass implements the abstract method, AbstractMethod, by specifying the override modifier.

Notice the virtual modifier on the ImplementedMethod method. This means that derived classes can override this method with their own implementation. An abstract class method doesn't need the virtual modifier, but its usefulness could be limited without it.

Encapsulation

C# classes have members, such as indexers, methods, and properties, that help encapsulate the internal state of a type. Visibility of type members is controlled with a set of modifiers, shown in Table 3.1. These modifiers control the interface of a type to external types.

Table 3.1 Visibility Modifiers

Visibility Modifier

Who Can See

public

All other types

protected

Derived types

internal

Types within the same assembly

protected internal

Types within the same assembly and derived

private

Within the same type only


Listing 3.8 and Listing 3.9 show how to use the visibility modifiers to control the public interface of a class.

Listing 3.8 Calling Class for Visibility Modifier Demo (Visibility.cs)

using System;

internal class ExternalDerived : PublicClass
{
  internal void ExternalDerivedMethod()
  {
   Console.WriteLine("External Derived Method");
   ProtectedMethod();
  }
}

class Visibility
{
  static void Main()
  {
   PublicClass myPublicClass = new PublicClass();
   myPublicClass.PublicMethod();

   ExternalDerived myExternalDerived = new ExternalDerived();
   myExternalDerived.ExternalDerivedMethod();

   Console.ReadLine();
  }
}

Listing 3.9 Called Class for Visibility Modifier Demo (CalledLibrary.cs)

using System;

internal class BaseInternal
{
  public void BaseInternalMethod()
  {
   Console.WriteLine("Internal Method.");
  }

  protected internal void ProtectedInternalMethod()
  {
   Console.WriteLine("Protected Internal Method.");
  }
}

internal class DerivedInternal : BaseInternal
{
  internal void DerivedInternalMethod()
  {
   ProtectedInternalMethod();
  }
}

public class PublicClass
{
  public void PublicMethod()
  {
   Console.WriteLine("Public Method.");

   BaseInternal myBaseInternal = new BaseInternal();
   myBaseInternal.BaseInternalMethod();

   DerivedInternal myDerivedInternal = new DerivedInternal();
   myDerivedInternal.DerivedInternalMethod();
  }

  protected void ProtectedMethod()
  {
   Console.WriteLine("Protected Method.");
   PrivateMethod();
  }

  private void PrivateMethod()
  {
   Console.WriteLine("Private Method.");
  }
}

Here is the output of running this program, demonstrating the sequence in which the methods execute:

Public Method.
Internal Method.
Protected Internal Method.
External Derived Method
Protected Method.
Private Method.

This is going to be a little complex, so look at each modifier in Listings 3.8 and 3.9 before following the explanation. Be sure to make Listings 3.8 and 3.9 separate projects. Listing 3.8 will be a console application and Listing 3.9 will be a class library. Creating a console application is explained in Chapter 1, which is something that has to be done for each of the other programs in Chapters 2 through 4.

To create an assembly for Listing 3.9, right-click on the project group and select Add New Project (see Figure 3.1). When the New Items dialog appears, select the C# Projects folder (see Figure 3.2) and then select the Class Library project type. Double-clicking the Class Library icon or clicking the OK button will bring up the New Project dialog. Give the project a name and directory and click the Create button.

Figure 3.1Figure 3.1 Adding a project from the Project Manager.

Figure 3.2Figure 3.2 Creating a class library project from the New Items dialog.

For a program to use a class library, it must reference it in the Project Manager. Expand the folder of the application for Listing 3.8 to reveal the References folder. Right-click on the References folder and select Add Reference. When the Add Reference dialog appears (see Figure 3.3), select the Project References tab, which exposes a list of all the projects in the current project group. Select the project for Listing 3.9 and click the Add Reference button. When the project name appears in the New References list, click the OK button. This places a reference from the console application project for Listing 3.8 to the class library project for Listing 3.9 in the References folder list (see Figure 3.4). In this example I named the console application project for Listing 3.8 as Visibility and the class library project for Listing 3.9 as CalledLibrary. To run the program, make sure that Listing 3.8 is the active project by double-clicking its project name, or right-click and select Activate from the context menu.

Figure 3.3Figure 3.3 The Add Reference dialog.

Figure 3.4Figure 3.4 Reference to a Class Library project.

When the CalledLibrary project reference is first added to the Visibility project reference list, the following error message will appear in the Build tab of the Messages window:

"[References Error] Could not find the assembly "CalledLibrary" on the 
Assembly Reference Search Path, or in the Global Assembly Cache." 

If your Messages window is not open, choose Tools, Options and make sure the Show Command Line box is checked on the Environment Options page of the Options dialog. There will also be a small red x on the icon for the CalledLibrary reference in the Visibility project's References folder. The message and error icon indicate that the CalledLibrary has not been compiled yet. To compile both projects and eliminate these errors, select the Visibility project title and select Build from the context menu. Running the project by pressing F9 or selecting Run, Run Without Debugging will also get rid of the errors. C#Builder will automatically detect whether projects and their references need to be compiled and will compile those items that need it prior to execution.

First, let's trace the code from the Main method of Listing 3.8. The first method call is to PublicMethod in Listing 3.9, which is declared public. PublicMethod is the only method of PublicClass that can be called because the other two methods are inaccessible to the Visibility class. PrivateMethod may only be accessed by members within PublicClass, and Visibility cannot get to ProtectedMethod because it does not inherit from PublicClass.

The only way to get to the code in the assembly for Listing 3.9 is through the public and protected methods of PublicClass, which is public. The other classes, DerivedInternal and BaseInternal, are declared internal, which means that only code within the same assembly may access them. Additionally, the ProtectedInternal method of the BaseInternal class is only accessible via the DerivedInternal class because its modifier only allows derived types within the same assembly to access it.

The PublicMethod method of PublicClass can access the BaseInternalMethod method of BaseInternal because it is within the same assembly. The same access applies to the DerivedInternalMethod method of DerivedInternal because it is also in the same assembly. The modifiers of BaseInternalMethod and DerivedInternalMethod demonstrate that types in an assembly may access public and internal members, respectively, of internal types within the same assembly. Finally, the ProtectedMethod of PublicClass has access to PrivateMethod because both are members of the same type.

The next call in the Main method of the Visibility class is to the ExternalDerived class, which is declared internal itself. I named it ExternalDerived because of its relationship to PublicClass. It is not internal to code in Listing 3.9 and derives from PublicClass. Remember that Listing 3.9 is a separate assembly. Because ExternalDerived is derived from PublicClass, it can call ProtectedMethod.

Polymorphism

Polymorphism—the ability of multiple types to be treated the same way—is implemented in C# with the virtual and override modifiers. The first declaration of an indexer, method, or property in a base class intended to support polymorphism will be decorated with the virtual modifier. Derived types wanting to implement polymorphism would decorate applicable members with the override modifier. Listing 3.10 demonstrates how to set up and implement polymorphism.

Listing 3.10 Implementing Polymorphism (Polymorphism.cs)

using System;

public class BaseClass
{
  public virtual void RunMe()
  {
   Console.WriteLine("BaseClass.");
  }
}

public class DerivedClass1 : BaseClass
{
  public override void RunMe()
  {
   Console.WriteLine("DerivedClass1.");
  }
}

public class DerivedClass2 : BaseClass
{
  public override void RunMe()
  {
   Console.WriteLine("DerivedClass2.");
  }
}

class Polymorphism
{
  static void Main()
  {
   BaseClass[] polyTypes =
   {
     new BaseClass(),
     new DerivedClass1(),
     new DerivedClass2()
   };

   foreach (BaseClass polyType in polyTypes)
   {
     polyType.RunMe();
   }

   Console.ReadLine();
  }
}

In Listing 3.10, DerivedClass1 and DerivedClass2 inherit BaseClass. Because BaseClass declares RunMe as virtual, both derived classes can override RunMe, which they do by using the override keyword and redefining their own versions of RunMe.

The power of this capability is demonstrated in the Main method, where polyTypes is declared as an array of type BaseClass and initialized with three objects. Because the array type is BaseClass, derived types can also be added. Because of the inheritance relationship, they are both their own specific type and BaseClass types.

The foreach loop iterates through the polyTypes array calling each object's RunMe method. Because their derived types override RunMe, polymorphism allows their methods to be invoked through a base class reference at runtime.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020