Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Inheritance 101 : Page 3

Extend your knowledge of inheritance to more easily extend your .NET applications.


advertisement
Preserving Differences
As you have just seen, inheritance provides for sharing similarities among classes. But inheritance also provides for preserving differences between them.

The Fish and Shark classes share the same properties as the Water class. They could also inherit directly from the OceanElement class, and the result would look very similar to the Water class shown in the prior code snippet.

However, there is a key difference between the Water class and the Fish and Shark classes: the water does not move during the simulation but the fish and sharks do.

To preserve this difference, define a separate SeaCreature class. The SeaCreature class inherits from OceanElement so that it shares the Image and Location properties, but then extends the OceanElement class by adding a Move method and a Random property. The result is as follows:

Public MustInherit Class SeaCreature Inherits OceanElement Public Overridable Sub Move(ByVal newOcean _ As Ocean) newOcean.putObject(Me) End Sub Protected Shared Rnd As Random = _ New Random(Now.Millisecond) End Class

The Fish and Shark classes then inherit from the SeaCreature class as shown with the Fish class:

Public Class Fish : Inherits SeaCreature Private Shared myImage As Image = _ Image.FromFile("../fish.jpg") Public Overrides ReadOnly Property Image() _ As Image Get Return myImage End Get End Property Public Overrides Sub Move( _ ByVal newOcean As Ocean) Dim n As Integer = Rnd.Next(1, 5) Dim p As Point Select Case n Case 1 p = newOcean.northOf(myLocation) Case 2 p = newOcean.eastOf(myLocation) Case 3 p = newOcean.southOf(myLocation) Case 4 p = newOcean.westOf(myLocation) End Select

 
Figure 2. WA-TOR Class Heirarchy: Sharks and Fish are SeaCreatures; SeaCreatures and Water are OceanElements. This defines the hierarchy of classes for the WA-TOR simulation.
If (newOcean.getObject(p).GetType. _ Equals(GetType(Water))) Then newOcean.putObject(New Fish(myLocation)) myLocation = p newOcean.putObject(Me) Else MyBase.Move(newOcean) End If End Sub Public Sub New(ByVal location As Point) myLocation = location End Sub End Class
By inheriting from the SeaCreature class, the Fish and Shark classes get all of the properties of the OceanElement class and the properties and methods of the SeaCreature class. This hierarchy of classes is shown in Figure 2.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date