480 likes | 691 Views
CSCI 3327 Visual Basic Chapter 3: Classes and Objects . UTPA – Fall 2011. Objectives. In this chapter, you will Become aware of reasons for using objects and classes Become familiar with classes and objects. Introduction. The book uses car analogy
E N D
CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011
Objectives • In this chapter, you will • Become aware of reasons for using objects and classes • Become familiar with classes and objects
Introduction • The book uses car analogy • We humans are very good in recognizing and working with objects, such as a pen, a dog, or a human being. • We learned to categorize them in such a way that make sense to us. We may categorize them as animate object, inanimate objects, pets, friends, etc.
Introduction (cont'd) • We some times classify objects based on their attributes, for example, green apples or red apples, fat or slim people, etc. • If you think about it each object has many attributes. If I ask you list the attributes of an orange, you probably could list many things such as color, shape, weight, smell, etc.
Introduction (cont'd) • In addition to attributes, all objects exhibit behaviors • A dog eats, barks, wags its tail, plays, and begs. A dog exhibits many more other behaviors than this short list • Another thing we need to remember about objects is that objects interact between each other
Objects • Objects are packages that contain data and functions (methods) that can be performed on the data.
Objects (cont'd) • Data could be considered to be attributes and functions are considered to be behaviors of the object. • We can say that the attributes and behaviors are encapsulated into an object.
Objects (cont'd) • The objects interact between each other through their interfaces. • As an example a date object may have a set of data consisting of month, day and year, and methods consisting of assign date, display date, yesterday and tomorrow.
Classes and Objects in Visual Basic • Classes are types and Objects are instances of the Class. • Without objects you cannot use a class • Your book says you cannot drive the drawing of a car • In Visual Basic, we create a class with the Class statement and end it with End Class
A Class Looks Like This: PublicClass HousePublic Rooms As Integer End Class
Members of a Class • Fields, Properties, Methods and Events • They can be declared as Public, Private, Protected, Friend or Protected Friend • Fields and Properties represent information that an object contains • Fields of a class are like variables and they can be read or set directly • For example, if you have an object named House, you can store the numbers of rooms in it in a field named Rooms
The Syntax for a Class • Public Class Test'-----Variables'-----Methods'-----Properties'-----EventsEnd Class
Instance Variables (Attributes) Examples: Amount of gas in your car Balance in your bank account
Using Objects • Object: car • Pressing the gas pedal sends a message to the car to perform a task • Similarly, in programming, you use a method call to send a message to the object
Methods (Behavior) • Methods represent the object’s built-in procedures. • For example, a Class named Country may have methods named Area and Population.
Defining Methods • You define methods by adding procedures, Sub routines or functions to your class • For example, implementation of the Area and Population methods discussed above might look like next slide
Example of Defining Methods Public Class Country Public Sub Area()Write("--------") End Sub Public Sub population()Write("---------") End Sub End Class
Properties (Attributes) • Properties are retrieved and set like fields • If they are public, they can be changed by clients • Private properties are implemented using Property Get and Property Set procedures which provide more control on how values are set or returned
Properties (cont'd) • Get and set appear to be similar to declaring the properties public • Through get and set, programmer can have control over setting the properties • For instance, if a client tries to set a date to 37, it can be checked and set to a default value instead
Example GradeBook • Public Class GradeBook • Private courseNameValue As String = "Not set yet" • Public Property CourseName() As String • Get • Return courseNameValue • End Get • Set(ByVal value As String) • courseNameValue = value • End Set • End Property • Public Sub displayMessage() • Console.WriteLine("Welcome to the grade book for " & vbNewLine & courseName & "!") • End Sub • End Class
Example Module • Module GradeBookTest • Sub Main() • Dim theName As String • Dim gradebook As New GradeBook • Console.WriteLine("Initial course name is: " & gradebook.CourseName & vbNewLine) • Console.WriteLine("Please enter course name: ") • theName = Console.ReadLine() • gradebook.CourseName = theName • Console.WriteLine() • gradebook.displayMessage() • Console.ReadKey() • End Sub • End Module
Events • We have been programming for events already • Events allow objects to perform actions whenever a specific occurrence takes place • For example, when we click a button a click event occurs and we can handle that event in an event handler
Creating An Object • After defining a class, instance of the class, object can be created • To create a object for this class (Test) we use the new keyword and that looks like this: • Dim obj AsNew Test()
Imports System.Console ModuleModule1 Sub Main() Dim obj As New Test obj.disp() Read() End Sub End Module Public Class Test Sub disp() 'a method named disp in the class Write("Welcome to OOP") End Sub End Class Sample Program
Classes • Constructor • Destructor • Properties • Methods • Inheritance • Polymorphism
Constructor • A constructor is a special member function whose task is to initialize the objects of its class • A constructor is invoked whenever an object of its associated class is created
Constructor (cont'd) • If a class contains a constructor, then an object created by that class will be initialized automatically • We pass data to the constructor by enclosing it in the parentheses following the class name when creating an object • In Visual Basic we create constructors by adding a Sub procedure name New to a class
Initializing Objects with Constructors in Visual Basic • The constructor class is called by the class name followed by parenthesis. • Constructor subroutine can be declared with the "New" keyword. • Public Sub New (ByValinitialBalanceAs Decimal) • Set default value in the constructor • Public Sub New (Optional ByValinitialBalanceAs Decimal = 0D)
Imports System.Console Module Module2 Sub Main() Dim startObject AsNewConstructor (10) 'storing a value in the constructor by passing a value(10) WriteLine(startObject.display()) 'calling it with the display method Read() 'reading from keyboard End Sub End Module PublicClassConstructor Public x AsInteger Public Sub New (ByVal value As Integer) 'constructor x = value 'storing the value of x in constructor End Sub PublicFunction display() AsInteger Return x 'returning the stored value End Function End Class
Destructor • Destructors run when an object is destroyed • Within a destructor we can place code to clean up the object after it is used • We use "Finalize" method in Visual Basic • The Finalize method is called automatically when the .NET runtime determines that the object is no longer required
Destructor (cont'd) • When working with destructors we need to use the overrides keyword with Finalize method as we will override the Finalize method built into the Object class • We normally use Finalize method to deallocate resources and inform other objects that the current object is going to be destroyed • The following code demonstrates the use of Finalize method
Imports System.Console ModuleModule3 Sub Main() Dim obj AsNewDestructor End Sub End Module PublicClassDestructor ProtectedOverridesSub Finalize() Write(“Destroyed!") Read() EndSub End Class
Property Values • Get and Set • Get allows you read the current property value • Set allows you to change the property value • Property without a "ReadOnly" or "WriteOnly" specifier must provide both a "Get" and a "Set"
Modules, Classes and Methods • Both classes and modules contain methods (Subs) • Related classes are grouped into namespaces and compiled into library files • A module contains declarations and procedures that are used by other files in a project • Module is not associated with a class or form and contain no event procedures • Good to use in case you are using multiple forms
Private and Public in a Module • Private – procedures and variables declared as private can only be accessed by statements in the same module • Public – accessible by statements either inside or outside the module • By default, Sub declarations are Public • Variables declared with Dim or Private – variables are private
Inheritance • A key feature of OOP is reusability • It's always time saving • It can be used by other programs to suit the program's requirement • This is done by creating a new class from an existing class • The process of deriving a new class from an existing class is called Inheritance
Inheritance (cont'd) • The old class is called the base class • The new class is called derived class • The derived class inherits some or everything of the base class • In Visual Basic we use the Inherits keyword to inherit one class from another
Inheritance (cont'd) • New class is created from an existing one by adding new or modified capabilities • The new class is a derived class or subclass • A derived class can become a base class for a future derived class • Is-a relationship – represents inheritance • A car is a vehicle • Has-a relationship – represents a composition • A car has a steering wheel
Inheritance Coding PublicClass One------End ClassPublicClass TwoInherits One------EndClass
Inheritance Coding (cont'd) Imports System.Console Module Module4 Sub Main() Dim ss AsNew Two WriteLine(ss.sum()) Read() EndSub EndModule (see next slide for inheritance)
PublicClassOne Public i AsInteger = 10 Public j AsInteger = 20 PublicFunction add() As Integer Return i + j End Function End Class Public Class Two InheritsOne Public k AsInteger = 100 PublicFunction sum() AsInteger 'using the variables, function from base class and adding more functionality Return i + j + k 'Return add() +k EndFunction EndClass
Protected Members • Public and Private • In the base class, private members are not inherited by derived classes • Protected access offers an intermediate level of access between Public and Private. • A base class’s protected members can be accessed only by members of that base class and by members of its derived classes
Friend Members • Friend access is another intermediate level access • If a program uses multiple classes from the same assembly, these classes can access each other’s friend members • Unlike public access, programs that are declared outside the assembly cannot access these Friend Members
Polymorphism • It means "one name, multiple forms"
Example of Polymorphism • Suppose there is a base class called Animal with a method called move • There are three derived classes called fish, frog and bird • Program calls move to all three objects of the derived class • Fish swims, frog jumps, and birds fly • This is possible because of polymorphism
Polymorphism Analogy • If you are asked to open, you will know what to do depending on what the object you are working with: a door, a jar, an envelope, etc.
Abstract and Concrete Classes • Abstract Classes that are not used to make objects • Abstract classes are incomplete and are used only as base classes to make derived classes • Derived classes that can be used to instantiate objects are called concrete classes