Object-Oriented Features of Visual Basic .NET

Snoops

   

 
Migrating to .NET: A Pragmatic Path to Visual Basic .NET, Visual C++ .NET, and ASP.NET
By Dhananjay  Katre, Prashant  Halari, Narayana  Rao  Surapaneni, Manu  Gupta, Meghana  Deshpande

Table of Contents
Chapter 2.   New Features in Visual Basic .NET


Visual Basic .NET is now a full-fledged object-oriented language like VC++, Java, and Smalltalk. It offers all the features of an object-oriented language such as

  • Abstraction

  • Encapsulation

  • Inheritance (interface inheritance, implementation inheritance, and also visual inheritance in the case of Windows and Web Forms)

  • Polymorphism

Most Visual Basic developers wanted inheritance in the language and now Microsoft has provided the inheritance features in the language. Let us take a look at an example of a simple inheritance in Visual Basic .NET. We define a base class called Shape and a child class called Circle to illustrate the concept of inheritance in Visual Basic .NET.

The following class in the file has one method Draw and is uploaded in the SimpleInheritance folder. This class Shape is an abstract class, and it provides an empty method Draw , which can be implemented by the class, which inherits from the Shape class.

 graphics/icon01.gif Imports System  Public MustInherit Class Shape     Public Overridable Sub Draw()     End Sub  End Class 

The following code example defines the class Circle , which inherits from class Shape . Here class Circle has given implementation details for inherited method Draw . The file is uploaded in SimpleInheritance folder.

 graphics/icon01.gif Imports System  Public Class Circle     Inherits Shape     Public Overrides Sub Draw()        Console.WriteLine("This is from the Derived Class")        Console.ReadLine()     End Sub     Public Sub Draw(ByRef p_String As String)        Console.WriteLine(p_String)        Console.ReadLine()     End Sub  End Class 

In the following code example the Main method has been implemented. This method creates instances of class Shape and Circle . The file is uploaded in the SimpleInheritance folder.

 graphics/icon01.gif Module SimpleInheritanceModule     Sub Main()        Dim objCircleOverride As Shape        objCircleOverride = New Circle()        objCircleOverride.Draw()        Dim objCircleOverlload As Circle        objCircleOverlload = New Circle()        objCircleOverlload.Draw()        objCircleOverlload.Draw("From the main module")     End Sub  End Module 

When the main module is executed, the CLR invokes the method of the Circle class named Draw and the string "This is from the Derived Class" gets executed. Even though the examples are very trivial, they illustrate several features of inheritance of the Visual Basic .NET language. The code examples explain concepts of inheritance, overriding, overloading, and polymorphism.

The class Shape is preceded by the keyword MustInherit . This means that the class Shape is an abstract class, which must be inherited by concrete classes.

In the derived class, there are two methods named Draw , which have different parameters. This illustrates the concept of overloading subprocedures in a class. The derived class also uses the same method name Draw , which is present in the base class Shape . However, the derived class provides its own implementation for the method. This concept is known as overriding.

There are several keywords related to inheritance, which can be applied to the classes:

  • MustInherit. This is an abstract class that cannot be instantiated using the new operator. It has to be extended by concrete classes.

  • NonInheritable. This is a type of class that cannot be inherited from by other classes. It is also sometimes referred to as a leaf class in the object-oriented world.

There are also several keywords related to inheritance that can be applied to the functions and subprocedures:

  • Overloads. This is used to declare a property or a function with the same name as an existing member, but with different arguments.

  • Overrides. This is used to signify that the method in the derived class overrides the method of the same name in the base class. The overridden method has the same signature in the derived and base classes.

  • Notoverridable. This is used in the base class to signify that any derived classes cannot override the method of the base class.

  • Shadows. This indicates that a declared programming element shadows an identically named element, or set of overloaded elements, in a base class. You can shadow any kind of declared element such as a function, a subprocedure, or a property.

Shadowing also works for scope. An entity's declaration may contain a nested declaration of entities with the same name. In this case, the nested entity shadows the outer entity. Shadowing through nested declarations occurs implicitly. For example, a variable can be declared at the class scope. A method can declare the same variable. In this method, the local variable hides or shadows the class-level variable.

The following code example is found in the folder ShadowsExample for this chapter. In this example, the parent class BaseClass defines two overloaded methods called Display . The following code shows the base class:

 graphics/icon01.gif Public Class BaseClass     Public Overridable Sub Display()        Console.WriteLine("Sub procedure with no " &_         "parameter in the base class")      End Sub      Public Overridable Sub Display(ByVal p_DisplayString _       As String)          Console.WriteLine("Sub procedure with a " &_           "string parameter in the base class")      End Sub  End Class 

In the derived class, the same method signatures are used with the addition of the keyword shadows in front of the subprocedure name as shown in the class DerivedClass :

 graphics/icon01.gif Public Class DerivedClass     Inherits BaseClass     Public Shadows Sub Display()        Console.WriteLine("Sub procedure with no " &_         "parameter in the derived class")     End Sub     Public Shadows Sub Display(ByVal p_DisplayString _      As String)        Console.WriteLine("Sub procedure with a string " &_         "parameter in the derived class")     End Sub  End Class 

In this example the subprocedures in the derived class have been shadowed and hence runtime polymorphism will not work. The main module is as follows :

 graphics/icon01.gif Module Module1     Sub Main()        Dim objDerivedClass As DerivedClass        ObjDerivedClass = new DerivedClass()        objDerivedClass.Display()        Console.ReadLine()        Dim objBaseClass As BaseClass = New DerivedClass()        objBaseClass.Display()        Console.ReadLine()     End Sub  End Module 

Note that in the main module references of DerivedClass and BaseClass were obtained. They are made to point to an object of type DerivedClass . The output from the execution of the code writes two lines of output. The first string "Sub procedure with no parameter in the derived class" is output when the reference object is of type DerivedClass . In the next case, when the reference object is of type BaseClass , the string "Sub procedure with no parameter in the base class" is output. Thus it can be seen that even though the reference type is of base class and the object that it refers to is of the derived type, the method from the base class gets executed. This concept is known as shadowing or scope hiding.

Visual C++ developers are familiar with the concept of multiple inheritance. It means that a class can be derived from multiple classes. Even though object-oriented features have been added to the Visual Basic .NET language, multiple inheritance is not allowed in Visual Basic .NET. This means that a class cannot inherit or extend from more than one class.

Visual Basic .NET also allows developers to define to their own interfaces, which are abstractions that define the operations. The implementation of these operations is not defined in the interface. Rather the operations are empty. Classes, which implement the interfaces, must provide their own implementation.

Interfaces are useful because they allow the Visual Basic .NET language to implement dynamic polymorphism. At runtime only a reference to the interface is required. The same reference can be made to point to the different objects in the classes that implement this interface. The codes from these objects can be executed depending on the object that the interface points to. This means that the objects can be accessed using a common reference variable of type interface and the same methods can call the various objects that implement these interfaces. Thus runtime polymorphism can be achieved.

Let us look at examples of interfaces and classes implementing those interfaces in Visual Basic .NET.

The following code example declares a simple interface with a single method called Draw . Note that it is a method with no body. Any class that implements the preceding interface must provide an implementation for the method Draw . This interface is defined in file Ishape.vb . The folder InterfaceDeclaration contains the following interface declaration:

 graphics/icon01.gif Public Interface IShape     Sub Draw()  End Interface 

Note that the interface is defined in Class Library project in Visual Studio .NET.

The following code example shows a class called myCircle that implements the preceding interface. This code can be found in the folder ImplmentingInterfaces for this chapter. A reference to the preceding project ( InterfaceDelcaration ) is added to the project, which needs to implement the preceding interface. Also, another class called myRectangle , which implements the same interface, is shown.

 graphics/icon01.gif Public Class myCircle : Implements _   InterfaceDeclaration.IShape     Dim objGraphics As Graphics     Dim clntRectangle As Rectangle     Public Sub New()     End Sub     Public Sub New(ByVal p_objGraphics As Graphics, _      ByVal p_clntRectangle As Rectangle)        objGraphics = p_objGraphics        clntRectangle = p_clntRectangle     End Sub     Public Sub Draw() Implements _      InterfaceDeclaration.IShape.Draw        objGraphics.DrawEllipse(Pens.Blue, clntRectangle)     End Sub  End Class  Public Class myRectangle : Implements _   InterfaceDeclaration.IShape     Dim objGraphics As Graphics     Dim clntRectangle As Rectangle     Public Sub New()     End Sub     Public Sub New(ByVal p_ObjGraphics As Graphics, _      ByVal p_clntRectangle As Rectangle)        objGraphics = p_ObjGraphics        clntRectangle = p_clntRectangle     End Sub     Public Sub Draw() Implements _      InterfaceDeclaration.IShape.Draw         objGraphics.DrawRectangle(Pens.Green, clntRectangle)     End Sub  End Class 

These classes implement the interface InterfaceDeclaration:Ishape . The Implements keyword is also used at the method level. This indicates that the method provides an implementation for a specific method of an interface. The preceding classes will be used in a Windows application. The Windows Form contains a RadioButton pair. This allows the user to select either a circle or a rectangle to draw a PictureBox control on the form. There is a ButtonBox labeled Draw to draw the selected shape and another one labeled Exit to end the application.

 graphics/icon01.gif Private Sub cmdExit_Click(ByVal sender As _   System.Object, ByVal e As System.EventArgs) _    Handles cmdExit.Click  End  End Sub  Private Sub cmdDraw_Click(ByVal sender As _   System.Object, ByVal e As System.EventArgs) _    Handles cmdDraw.Click     Dim objShape As InterfaceDeclaration.IShape     Dim objGraphics As Graphics     objGraphics = Me.CreateGraphics()     objGraphics.Clear(PictureBox1.BackColor)     If (RadioButton2.Checked = True) Then        objShape = New myCircle(objGraphics, _         PictureBox1.ClientRectangle)     End If     If (RadioButton1.Checked = True) Then        objShape = New myRectangle(objGraphics, _         PictureBox1.ClientRectangle)       End If     objShape.Draw()  End Sub 

The main module shows that in Visual Basic .NET we can obtain a reference to an interface and then assign a specific instance of the object that implements the specific interface. This is known as dynamic binding and is useful in achieving polymorphism, which is the most important aspect of object-oriented programming.


Snoops

   
Top


Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
ISBN: 131009621
EAN: N/A
Year: 2001
Pages: 149

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net