Thursday, December 13, 2007

VB .NET Tip: Overriding vs Overloading vs Shadowing

คอนเซ็บ ของ OOP ระหว่าง Overriding , Overloading , Shadowing มีความแตกต่างกันดังนี้ :



Overriding
This method completely replace a base class method implementation. It uses the same signatures (Parameters and return values) but you add new statements from the original code or completely change the process. Here is a good example of Overriding in VB .NET:



'The Original Class
Public Class MyBaseClassSample

Public Overridable Function MyFunc(ByVal X as Integer, ByVal Y as Integer) as Integer
Retun X * Y
End sub

End Class

'The Derived Class
Public Class MyNewClassSample

Inherits MyBaseClassSample
Public Overrides Function MyFunc(ByVal X as Integer, ByVal Y as Integer) as Integer
'Take note: It accepts and return same values but it changes the process
Retun X + Y
End sub

End Class



Overloading
Think Overloading as expanding the versions of a method. You don't change the original method of the base class but you add new versions of it. To create new version of a method you must define new parameters or return new type of value. Here is an example of Overloading:


'The Original Class
Public Class MyBaseClassSample

Public Overridable Function MyFunc(ByVal X as Integer, ByVal Y as Integer) as Integer
Retun X * Y
End sub

End Class

'The Derived Class
Public Class MyNewClassSample

Inherits MyBaseClassSample

'Version 2: accepts new parameter
Public Function MyFunc(ByVal X as Integer, ByVal Y as Integer, ByVal Z as Integer) as Integer
Retun X * Y * Z
End sub

'Version 3: return new type
Public Function MyFunc(ByVal X as Integer, ByVal Y as Integer, ByVal Z as Integer) as String
Retun "Answer is: " & (X * Y * Z)
End sub

End Class



Shadowing
This method has the characteristic of both Overloading and Overriding, You create a new version of a method (overloading) but you want the orignal version be hidden from the user of the derived class (overriding). To make it crystal clear, look at the following example:


'The Original Class
Public Class MyBaseClassSample

Public Overridable Function MyFunc(ByVal X as Integer, ByVal Y as Integer) as Integer
Retun X * Y
End sub

End Class

'The Derived Class
Public Class MyNewClassSample

Inherits MyBaseClassSample

'Version 2: accepts new parameter
Public Shadows Function MyFunc(ByVal X as Integer, ByVal Y as Integer, ByVal Z as Integer) as Integer
Retun X * Y * Z
End sub


End Class

'Client code

Dim MyShadowFunc as New MyNewClassSample ()

MyShadowFunc.MyFunc(3, 4) ' Generates error since this is the original method implementation

MyShadowFunc.MyFunc(3, 4, 5) ' Correct method

No comments: