Thursday, December 04, 2003

Interface and Abstract Class - Part 2


What is an Abstract Class?

An abstract class has a couple of features that are similar to an interface: You can't instantiate an abstract class and it can contain method and property signatures. The main difference from an interface is that the abstract class can provide implementation to methods, etc.

An example abstract class could be one used for encrypting files:


Public MustInherit Class AbstractFileEncryptor
 
Public Property Key() As String
'code for the property
End Property
 
Public Property Source() As String
'code for the property
End Property
 
Public Property Target() As String
'code for the property
End Property
 
'An abstract method
Public MustOverride Sub Encrypt()
 
End Class

We give implementation to the Key, Source and Target properties because they will be used in all sub-classes and they will all have the same functionality. However we have no clue how the Encrypt() method will be implemented because the sub-classes will be for different encryption algorithms. For example:


Public Class RSAFileEncryptor : Inherits AbstractFileEncryptor
Public Overrides Sub Encrypt()
'code to implement RSA encryption
End Sub
End Class

Tomorrow: When to use which.

No comments: