03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Inheritance ❘ 261<br />

Ann: Person.HideMe<br />

Bob: Employee.HideMe<br />

Bob: Person.HideMe<br />

The object person invokes the Employee class’s version of IsVirtual (the third line of output) but it<br />

invokes the Person class’s version of HideMe (the last line of output).<br />

TIP Hiding and overriding are important but confusing concepts. If the difference<br />

isn’t clear, you should reread this section.<br />

There are two other keywords that affect overriding: abstract and sealed.<br />

abstract<br />

An abstract method is one that doesn’t have a method body. It defines the name, parameters, and<br />

return type of the method but doesn’t provide an implementation. (This is similar to the way interfaces<br />

define method signatures but don’t provide an implementation.)<br />

If you give a class an abstract method, there’s a sort of placeholder in the class for the method. Because<br />

the placeholder is empty, you cannot create an instance of the class because it is incomplete. For that<br />

reason, if a class contains an abstract method, you must also mark the class as abstract.<br />

Note that the class could define other non-abstract properties, methods, and events. (Some people<br />

call a non-abstract method, class, or other item concrete.) If it contains even one abstract method,<br />

then the class must be abstract.<br />

Absolutely Abstract<br />

You can also mark a class abstract to prevent someone from creating an instance<br />

of it even if it doesn’t contain any abstract methods.<br />

An abstract method is also considered virtual, so a child class can override it to give it a method<br />

body. Then the child class can be concrete and you can create instances of it.<br />

For an example, consider the following code.<br />

public abstract class Report<br />

{<br />

public abstract void GenerateReport();<br />

public abstract void DistributeReport();<br />

}<br />

public abstract class PersonnelReport : Report<br />

{<br />

public override void DistributeReport()<br />

{<br />

// Code to distribute the report to the personnel department...<br />

}<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!