Introduction to Object-oriented programming
Java is an object-oriented programming language. Visual Basic has many object attributes, but it is not a strict object-oriented language. In this section, we'll show you how to build a class in Visual Basic, and then explain how to build an equivalent class in the Java language.
Use of Classes
You can think of a class as a data type that you want to define. A variable instance of a class is called an object. Unlike other variables, an object has a type, a set of properties, and a set of actions. The type of an object can be represented by the class used when the object is instantiated. The property of the object represents the value or state of the object. Object is the set of all functions that you invoke to change the state of the object.
Consider the basic data type integer for Visual Basic, which represents an integer. You can use this type to create a number of variables that are instances of an integer. Each integer variable has an attribute that indicates that the variable holds an integer value. Each Integer variable has the same set of actions that can modify the state (or value) of the variable. The actions you can take on an Integer variable include: Add (+), subtract (-), multiply (*), except (\), and modulo (Mod).
Defining Visual Basic Classes
Now let's assume that you want to develop a type of your own-it can represent a complex object, and the basic type in the Visual Basic language does not support this type. Suppose you are a member of a financial system software development team, and your task is to develop some code to represent a typical bank account number. Although a bank has many kinds of accounts, but each account has some of the same basic attributes and operations. Specifically, each account has a balance and an ID number. The Visual Basic code given in Listing 10 defines an account class. Three actions are defined in this class: deposit, withdrawal, and initaccount (used to initialize account balances and account numbers). Notice how you use a private variable to record the actual account balance and define a property named Balance to allow the user who uses the class to obtain the account balance.
Listing 10. Defining Visual Basic Classes
Private theBalance As Currency
Private theAccountNumber As Integer
Public Sub InitAccount (number As Integer, initBal As Currency)
theAccountNumber = number
theBalance = initBal
End Sub
Public Sub Deposit (amount As Currency)
theBalance = theBalance + amount
End Sub
Public Sub Withdrawal (amount As Currency)
theBalance = theBalance - amount
End Sub
Public Property Get Balance() As Currency
Balance = theBalance
End Property
Public Property Get AccountNumber() As Integer
AccountNumber = theAccountNumber
End Property