30.07.2013 Views

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

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.

Chapter 10 Object-Oriented <strong>Program</strong>ming: Polymorphism 423<br />

21 ' property Age<br />

22 ReadOnly Property Age() As Integer _<br />

23 Implements IAge.Age<br />

24<br />

25 Get<br />

26 Return mRings<br />

27 End Get<br />

28<br />

29 End Property ' Age<br />

30<br />

31 ' property Name implementation of interface IAge<br />

32 ReadOnly Property Name() As String _<br />

33 Implements IAge.Name<br />

34<br />

35 Get<br />

36 Return "Tree"<br />

37 End Get<br />

38<br />

39 End Property ' Name<br />

40<br />

41 End Class ' CTree<br />

Fig. 10.17 CTeee class implements IAge interface (part 2 of 2).<br />

Class CTest (Fig. 10.18) demonstrates polymorphism on the objects of disparate<br />

classes CPerson and CTree. Line 11 instantiates object tree of class CTree, and line 12<br />

instantiates object person of class CPerson. Line 15 declares iAgeArray—an array<br />

of two references <strong>to</strong> IAge objects. Line 18 and 21 assign tree and person <strong>to</strong> the first<br />

and second reference in iAgeArray, respectively. Lines 24–26 invoke method<br />

ToString on tree, then invoke its properties Age and Name <strong>to</strong> return age and name<br />

information for object tree. Lines 29–31 invoke method ToString on person, then<br />

invoke its properties Age and Name <strong>to</strong> return age and name information for object<br />

person. Next, we manipulate these objects polymorphically through the iAgeArray of<br />

references <strong>to</strong> IAge objects. Lines 36–39 define a For-Each structure that uses properties<br />

Age and Name <strong>to</strong> obtain age and name information for each IAge object in iAgeArray.<br />

Note that we use Name so that each object in iAgeArray can “identify” itself in our program’s<br />

output. Objects tree and person can use method ToString <strong>to</strong> do this, because<br />

classes CTree and CPerson both inherit from class Object. <strong>How</strong>ever, when CTest<br />

interacts with these objects polymorphically, CTest can use only properties Age and<br />

Name for each interface object. Because interface IAge does not provide method<br />

ToString, clients cannot invoke method ToString through interface IAge references.<br />

1 ' Fig. 10.18: Test.vb<br />

2 ' Demonstrate polymorphism.<br />

3<br />

4 Imports System.Windows.Forms<br />

5<br />

6 Class CTest<br />

7<br />

Fig. 10.18 Demonstrate polymorphism on objects of disparate classes (part 1 of 2).

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

Saved successfully!

Ooh no, something went wrong!