If you ask an OOP guru what an OOP language is, you will probably hear him/her utter words such as class, interface, information hiding, encapsulation, inheritance, polymorphism, etc. Those sound cool, don't they? OOP, however, is a topic that is not too easy to master in a day or two or by just attending a lecture. To truly understand it, you need to know the theory as well as do some OOP coding practice. This article offers readers just getting into OOP the very basics of OOP, using VB.NET as the language. It is not a complete reference, but it is something to start with.
Have you wondered why modern programming languages tend to be object-oriented? C++ was created as an extension of C to support OOP. And Java, one of the most popular languages on the planet, is also an OOP language. Then, of course, VisualBasic has evolved into VB.NET, a fully OOP language. There is a good reason for this transformation. OOP offers several benefits, such as easy code maintenance, extensibility, and code reuse, not found in procedural programming languages. Some of the benefits are outlined below.
Now, let's look at some of the features of OOP, starting with the easiest one, classes.
Classes are the main focus in OOP. Simply put, a class is a data type that provides some functionality. A class in VB.NET is declared using the keyword
Class. For example, Listing 1 presents a class called
Listing 1: Class Employee
Class Employee End Class
As simple as that. Note that Microsoft recommends the use of Pascal-case naming for classes. This means the first character of a class name is uppercase, and so is the first letter of any subsequent concatenated words. Good class names according to this convention include
StringUtil, and so on.
|Do you find OOP important to your Visual Basic programming needs? Give some examples.|
A class can have members such as fields, properties and subroutines and functions. For example, Listing 2 presents the Employee class with a subroutine called
Listing 2: Class Employee with method Work
Class Employee Public Sub Work () ' Do something here End Sub End Class
Subroutines and functions are both called methods. Method names are also Pascal-case.
Another type of class member is a field. A field name is camel-case, which means you capitalize the first character of each word except the initial character. Examples of good field names are
quarterlyBonus, etc. Adding two fields called
yearlyBonus to the
Employee class in Listing 2 will result in the following code.
Listing 3: Class Employee with two fields
Class Employee Dim salary As Decimal = 40000 Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ' print the salary to the Console System.Console.Write(salary) End Sub End Class
A class is a template or a blueprint of the entity that the class represents. To use a class's field or method or any other member, you need to first turn the class into an object, just as the blueprint of a sports car is useless until assembly workers make the car. In other words, you drive a car, not the blueprint of a car.
In OOP, an object is said to be an instance of a class. Creating an object is therefore known as instantiation. The code in Listing 4 demonstrates the instantiation of the
Listing 4: Instantiating an object
Class Employee Dim salary As Decimal = 40000 Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ' print the salary to the Console System.Console.Write(salary) End Sub End Class Module Module1 Public Sub Main() Dim anEmployee As Employee anEmployee = New Employee() anEmployee.PrintSalary() End Sub End Module
Module1 in Listing 4 provides the
Main sub, which is the entry point of a VB.NET program. In order to compile, a source file must provide access to the
Main sub in one way or another. If you are not using Visual Studio.NET, you can compile your VB.NET program with vbc.exe, which is automatically installed when you install the .NET Framework. For instance, if you save your source code as Employee.vb, go to the directory where the file Employee.vb is stored, and then type
Now back to the code. The
Main sub first declares an object variable of type
Employee. The variable is called
Dim anEmployee As Employee
It then instantiates Employee with the keyword
anEmployee = New Employee()
Now that you have an object of type Employee, you can use its functionality. (Once the car is built, you can start and drive it.) In our example, we can call the
PrintSalary method as follows.
This will print the value of the
salary variable in
You can also move the
Main sub into the class. This way, you don't need a module. This approach is shown in Listing 5.
Listing 5: Moving the Main sub to the class itself
Class Employee Dim salary As Decimal = 40000 Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ' print the salary to the Console System.Console.Write(salary) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee.PrintSalary() End Sub End Class
System.Console.Write in the
PrintSalary method means that you call the
Write method of the
Console is part of the
System namespace. Namespaces are discussed next.
When you write a .NET program, you write classes and other types. To make your application more organized, you can group your classes into namespaces. This is also what Microsoft does with the .NET Framework class library. If you open the .NET Framework class library in the .NET Framework SDK documentation, you can see there are more than 80 namespaces. Important namespaces you will frequently use include
For example, in the
PrintSalary method in the
Employee class we used the
Console class in the
If you will be using a namespace often, you can import a namespace so that you don't have to repeat it every time you want to use its member. For instance, you can rewrite the code in Listings 4 and 5 as shown below.
Listing 6: Importing a namespace
Imports System Class Employee Dim salary As Decimal = 40000 Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ' print the salary to the Console Console.Write(salary) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee.PrintSalary() End Sub End Class
Now, you can use the
Console class in the
PrintSalary method without mentioning the namespace because the namespace is already imported.
Namespaces also allow you to have classes with the same name in different namespaces. To refer to a class correctly, it is common practice to mention the namespace in front of the class name. For example, the
Console class in the
System namespace is referred to as
In many cases, when you write a class, you will provide that class to other people so they can use its functionality, i.e., they can call methods of that class or access its fields. One of the great benefits of OOP is that you can restrict access to a class member. This means, you have full control over what you want to expose. You can write methods that can be called by other programmers, or you can have methods that are not accessible by anyone other than from inside the class itself.
VB.NET offers levels of accessibility, as follows:
Publicin front of the class member to make it available publicly. For example, the
PrintSalarymethod in the
Employeeclass is a public method. It can be called from anywhere.
Privatekeyword to make a class member private.
Protectedkeyword to make a member protected.
friendaccess restriction are accessible only within the program that contains the class declaration. Use the keyword
Friendto make a member have friend restriction.
These different access types provide for information hiding in OOP. In other words, you can protect class members that you don't want to expose.
Looking at the
Employee class in Listings 4, 5 and 6 again, you may wonder why we can use the
Write method of the
System.Console class without first instantiating a
System.Console object. This is because in OOP languages there is a special type of member called a static member. The term shared is also used in VB.NET.
Static means the member is available without having to instantiate an object. For example, the class called
SalaryLevel provides static fields only in Listing 7.
Listing 7: Static members in a class
Class SalaryLevel Public Shared Level1 As Decimal = 35000 Public Shared Level2 As Decimal = 40000 Public Shared Level3 As Decimal = 45000 Public Shared Level4 As Decimal = 50000 Public Shared Level5 As Decimal = 55000 Public Shared Level6 As Decimal = 60000 Public Shared Level7 As Decimal = 65000 Public Shared Level8 As Decimal = 70000 Public Shared Level9 As Decimal = 75000 Public Shared Level10 As Decimal = 80000 End Class
You can then use the class in your program, as illustrated in Listing 8.
Listing 8: Using a static member of a class
Imports System Class SalaryLevel Public Shared Level1 As Decimal = 35000 Public Shared Level2 As Decimal = 40000 Public Shared Level3 As Decimal = 45000 Public Shared Level4 As Decimal = 50000 Public Shared Level5 As Decimal = 55000 Public Shared Level6 As Decimal = 60000 Public Shared Level7 As Decimal = 65000 Public Shared Level8 As Decimal = 70000 Public Shared Level9 As Decimal = 75000 Public Shared Level10 As Decimal = 80000 End Class Class Employee Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ' print the salary to the Console, use the static field of SalaryLevel Console.Write(SalaryLevel.Level4) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee.PrintSalary() End Sub End Class
PrintSalary method of the
Employee class, we can use the
Level4 static field in the
SalaryLevel class without first creating an object of type
SalaryLevel. Members that are not static are called instance members.
A constructor is a special method that must be present in a class for the class to get instantiated. In VB.NET, this method is called
New. But, as you have seen, there is no
New method in the classes in the previous code. That's right. When there is no constructor present, VB.NET will create one for you. When you instantiate an object by using the
New keyword, the class's constructor is called. You can provide initialization code that is guaranteed to run when the object is instantiated.
If you write a constructor explicitly in your class, VB.NET won't create it anymore.
Inheritance is a feature that allows you to extend a class. If you need some functionality, you can create a brand new class. If part of the functionality you need has been provided in a class written by someone else, however, you can then write a new class that extends the original class. Your class is called the child class or derived class, and the original class is called the parent class or the base class. The process of extending a class is called extension. Sometimes, the term subclass or inherit is used to describe the act of extending a class. In VB.NET a class can only extend one parent class. Multiple class inheritance is not allowed in VB.NET.
Syntactically, extending a class is done using a semicolon after the class name, followed by the word
Inherits and the parent class name. For example, Listing 9 shows how we extend the class
Employee to create a new class called
Listing 9: Extending a class
Imports System Class Employee Dim salary As Decimal = 40000 Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ' print the salary to the Console Console.Write(salary) End Sub End Class Class Manager: Inherits Employee End Class
If the word
Inherits appears on the next line, you don't need the semicolon.
Class Manager Inherits Employee End Class
Now, you can instantiate a
Manager object and use members from the
The code is given in Listing 10.
//////QUESTION: IMPORTS SYSTEM WAS STUCK IN THE ABOVE GRAF. IT PROBABLY BELONGS AS TEH FIRST LINE OF CODE. CHECK WITH AU.//////////
Listing 10: Instantiating a Manager object
Imports System Class Employee Public salary As Decimal = 40000 Public yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ' print the salary to the Console Console.Write(salary) End Sub End Class Class Manager: Inherits Employee End Class Module Module1 Public Sub Main() Dim manager As Manager manager = New Manager() manager.PrintSalary() End Sub End Module
The example in Listing 11 shows how we can extend the
Manager class by writing a new method called
Listing 11: Adding a method to the derived class
Class Manager: Inherits Employee Public Sub PrintBonus() Console.Write(yearlyBonus) End Sub End Class
Note that member accessibility restriction applies. For example, you can't make the
yearlyBonus field private, since this field is not accessible from the
Manager class. Therefore, trying to compile the code will result in an error.
Inheritance is a common practice. In fact, the .NET Framework class library consist of hierarchies of classes that are derived from other classes. For example, the
Button class in the
Windows.Forms namespace is a child class of
ButtonBase, which itself is a child of
Control. All classes will eventually have the
System.Object class as its root.
System.Object is called the root or the superclass in the .NET Framework class library.
The power of inheritance can be demonstrated by the code in Listing 12.
Listing 12: Extending System.Windows.Forms.Form
Public Class MyForm : Inherits System.Windows.Forms.Form End Class
This blank class declaration, when compiled and run, will display a Windows form. You can create a form without a single line of code. This is because
System.WIndows.Forms.Form. It inherits the functionality of the
You can prevent classes from being inherited by using the
NotInheritable keyword. For example, the code in Listing 13 is a class called
Calculator that cannot be inherited.
Listing 13: A non-inheritable class
NotInheritable Class Calculator End Class
Trying to extend this class will raise a compile error. Why would you want to make your class non- inheritable? In some cases, you may not want other people to be able to extend your class. Another reason is that an inheritable class produces faster code. You should use inheritable classes with caution, however, because noninheritance defeats the purpose of OOP. Only use it if you are 100% sure that you will not extend the class. This type of class is also called a final class in some other OOP languages.
Part 2 of this series can be found here
Return to the .NET DevCenter.
Copyright © 2009 O'Reilly Media, Inc.