Title: Advanced Classes
1Advanced Classes
2Overview
- Value Types
- Objects and Reflection
- Interfaces
- Inheritance
- Collections
- Visual Inheritance
- Delegates
3Value Types
4Characteristics of Value Types
- assignment operator copies contents
- Dim N As Integer, M As Integer
- M N
- compared using relational operators (lt, gt, etc.)
- If M lt N Then ...
- New operator not required when creating instances
- Faster program execution
5Enums
- System.Enum is the base class for enumerated
types - inherits from System.Object
- Limited set of integral values
- Example
- Enum AccountType
- Checking 100
- Savings 101
- Trading 102
- Annuity 103
- End Enum
6Assigning Values to Enums
- Declare variable
- Dim acct As AccountType
- Assign value using Enum type as qualifier
- acct AccountType.Checking
- Cannot assign equivalent integers
- acct 101 'Error!
7Assigning Values to Enums
- GetType returns a System.Type object
- Dim acct As AccountType
- acct AccountType.Checking
- Dim T as Type acct.GetType()
- GetName returns enum variable's value
- AccountType.GetName( T, acct )
See the Objects.Enums program
8Objects and Reflection
9Reflection
- Finding out about objects at runtime
- get its type (its class)
- get list of members
- enabling class for advanced VB.NET features
- Runtime Type Identification
- TypeOf operator returns boolean value
- Dim myAcct As New Account
- TypeOf (myAcct) Is Account 'equals True
10Type Class
- Represents type declarations of classes,
interfaces, arrays, value types, and enumerations - System.Object.GetType method
- Function GetType( ) As System.Type
- System.Type methods
- FullName returns fully qualified class name
- ToString returns fully qualified class name
11System.Object Class
- Ultimate superclass (cosmic superclass)
- base class for all other classes
- Methods
- Function Equals( Object ) As Boolean
- Shared Function ReferenceEquals( Object, Object )
As Boolean - Function ToString( ) As String
- Function GetType( ) As Type
- Function GetHashCode( ) As Integer
- Function MemberwiseClone( ) As Object
12Overriding ToString
- Example from the Account class
- Must use the Overrides qualifier
- Public Overrides Function ToString() As String
- Return "AccountId " AccountId _
- ", Balance " FormatCurrency(Balance)
- End Function
13Comparing Objects
- Objects cannot be compared using , lt, gt, etc.
- Objects can be compared by Equals method
- Dim a1 As New Account, a2 As New Account
- If a1.Equals( a2 ) Then ...
- Object.Compare just compares object references
- i.e. their addresses
- For example
- a2 a1 'copy the reference
- If a1.Equals( a2 ) Then ... 'equals True
14Comparing Objects
- ReferenceEquals works the same as Equals
- Dim a1 As New Account, a2 As New Account
- If ReferenceEquals( a1, a2 ) Then ... 'False
- a2 a1
- If ReferenceEquals( a1, a2 ) Then ... 'True
15Overriding Object.Equals
- To compare the states of two objects, your class
must override Object.Equals - Simple contract
- comparing an object to Null returns False
- objects related by inheritance are never equal
- compare the values in one or more fields
16Account.Equals Example
- Arbitrary decision compare the account ID
values - Public Overrides Overloads _
- Function Equals(ByVal obj As Object) As Boolean
-
- If obj Is Nothing Then Return False
- If Not obj.GetType Is Me.GetType Then Return
False - Return AccountId CType(obj, Account).AccountId
- End Function
17Account.Equals Example
- Calling Equals
- Dim a1 As New Account(1001, 50.25D)
- Dim a2 As New Account(1001, 400D)
- Dim a3 As New Account(2002, 50.25D)
- Dim nv As Account Nothing
- WriteLine(a1.Equals(nv)) 'False
- WriteLine(a1.Equals(a2)) 'True
- WriteLine(a1.Equals(a3)) 'False
18Interfaces
19Defining an Interface
- Like a class, but not implemented directly
- All members are implicitly public
- Specifies methods, properties, types, events
- Interface keyword
- no implementations, just prototypes no fields
- Example IPayable
- Interface IPayable
- Function CalculateTax() As Decimal
- ReadOnly Property NetPay() As Decimal
- End Interface
20Implementing an Interface
- Class must use the Implements keyword
- Must implement all interface methods and
properties - if you plan to create class instances
- Example
- Class Employee
- Implements IPayable
- Public Function CalculateTax() As Decimal _
- Implements IPayable.CalculateTax
- ...
- End Function
- Public ReadOnly Property NetPay() As Decimal _
- Implements IPayable.NetPay
- ...
- End Property
- End Class
See Interfaces.IPayableExample
21Interface Parameters
- Functions can declare interface type parameters
- Sub ProcessPayroll(ByVal P As IPayable)
- WriteLine("Tax " FormatCurrency(P.Calcula
teTax())) - WriteLine("Net Pay " FormatCurrency(P.NetPay)
) - End Sub
- Pass objects as arguments if they implement the
interface - Dim emp As New Employee("Jones, Dan", 35000D)
- ProcessPayroll(emp)
- Output
- Tax 134.62
- Net Pay 1,211.54
22IComparable Interface
- Standard interface type in .NET
- Used by collection classes
- Implement in your class if objects will be
inserted in collections - Definition
- Interface IComparable
- Function CompareTo(ByVal obj As Object) As
Integer - End Interface
23Behavior of CompareTo
- A.CompareTo(null) returns a positive integer.
- A System.ArgumentException is thrown if A and B
are different types. - If A is less than B, A.CompareTo(B) returns a
negative integer. - If A is equal to B, A.CompareTo(B) returns zero.
- If A is greater than B, A.CompareTo(B) returns a
positive integer.
24Employee.CompareTo (version 1)
- Basic version
- Class Employee
- Implements IComparable
- Public Function CompareTo(ByVal obj As Object) As
Integer _ - Implements IComparable.CompareTo
- Dim emp2 As Employee CType(obj, Employee)
- Return CInt(mSalary - emp2.mSalary)
- End Function
- ...(etc.)
- End Class
25Employee.CompareTo (version 2)
- Why is this version better?
- Public Function CompareTo(ByVal obj As Object) As
Integer _ - Implements IComparable.CompareTo
- If obj Is Nothing Then Return 1
- If Not Me.GetType() Is obj.GetType() Then _
- Throw New ArgumentException
- Dim emp2 As Employee CType(obj, Employee)
- Return CInt(mSalary - emp2.mSalary)
- End Function
See Interfaces.EmployeeCompare
26Sorting an Array of Employees
- Sort executes correctly because Employee
implements IComparable - Dim staff(3) As Employee
- staff(0) New Employee("Jones, Dan", 65000D)
- staff(1) New Employee("Ramirez, Julio", 45000D)
- staff(2) New Employee("Bond, Barry", 55000D)
- staff(3) New Employee("Chong, Gary", 75000D)
- System.Array.Sort(staff)
27IComparer Interface
- Declaration
- Interface IComparer
- Function Compare(ByVal x As Object, _
- ByVal y As Object) As Integer
- End Interface
- Class defining the collection elements does not
directly implement IComparer
28Windmill Example
- RpmComparator compares the RPMs of windmills
- Structure Windmill
- Public rpm As Integer
- End Structure
- Class RpmComparator
- Implements IComparer
- Public Function Compare(ByVal x As Object, _
- ByVal y As Object) As Integer _
- Implements IComparer.Compare
- Return CType(x, Windmill).rpm - CType(y,
Windmill).rpm - End Function
- End Class
29Using RpmComparator
- RpmComparator compares the RPMs of windmills
- The following code builds and sorts the array in
ascending order by by rpm speed - Dim wind(4) As Windmill
- wind(0).rpm 50
- wind(1).rpm 45
- wind(2).rpm 72
- wind(3).rpm 55
- Array.Sort(wind, New RpmComparator)
See Interfaces.Comparators
30Inheritance
31Defining Inheritance
- Ability of a class to specialize the properties,
methods, and events of another class - Inherits keyword
- base class, derived class
- superclass, subclass
- Desktop VB .NET forms use inheritance
- Public class frmMain
- Inherits System.Windows.Forms.Form
32Access Modifiers
33Person Class Example
- Class Person
- Public Sub Display()
- WriteLine("Person " mName)
- End Sub
- Friend Property Name() As String
- Get
- Return mName
- End Get
- Set(ByVal Value As String)
- mName Value
- End Set
- End Property
- Protected ID As Integer
- Private mName As String
- End Class
34Inheriting from the Person Class
- Class Hero
- Inherits Person
- Sub TestAccess()
- Display() 'ok Public
- Name "Sam Jones" 'ok Friend
- ID 12345 'ok Protected
- mName "Joe Smith" 'error Private
- End Sub
- End Class
See Inheritance.Heroes_0
35Heroes and Villains
UML diagram
36Person, Hero, Villain
- Class Person
- Public Name As String
- End Class
- Class Hero
- Inherits Person
- Public Ability As String
- End Class
- Class Villain
- Inherits Person
- Public BadDeeds As ArrayList
- End Class
See Inheritance.Heroes_1
37Wizard
- Class Wizard
- Inherits Person
- Enum MagicSpecialty
- casts_spells
- casts_out_spirits
- vanishes
- speaks_in_tongues
- wisdom
- End Enum
- Public Specialty As MagicSpecialty
- End Class
38Creating Instances
- A Hero has a name and ability
- Dim H As New Hero
- H.Name "Superman"
- H.Ability "Invincible"
- A Villain has a name, along with a list of bad
deeds - Dim V As New Villain
- V.Name "Evil Witch"
- V.BadDeeds.Add("Casts spells")
- V.BadDeeds.Add("Turns princes into frogs")
- A Wizard has a name and a specialty
- Dim W As New Wizard
- W.Name "Merlin"
- W.Specialty W.MagicSpecialty.wisdom
39Inheritance with Constructors
- When constructing a derived object...
- default base class constructor is automatically
called before the derived class constructor
executes - If the base constructor has parameters...
- you must call it explicitly, passing arguments
40Example
- Class Person
- Sub New(ByVal name As String)
- mName name
- End Sub
- Private mName As String
- End Class
- Class Hero
- Inherits Person
- Sub New(ByVal name As String, ByVal ability As
String) - MyBase.New(name)
- mAbility ability
- End Sub
- Private mAbility As String
- End Class
See Inheritance.Heroes_2
41Assigning Object References
- Upward cast is automatic
- Dim P As Person
- Dim H As New Hero("Aquaman","Swims")
- P H
- Downward cast must be explicit
- Dim P As Person New Hero("Superman","Flies")
- Dim H As Hero CType(P, Hero)
- Invalid cast compiles, but throws an exception at
runtime - Dim P As New Person("Bob")
- Dim H As Hero CType(P, Hero)
42Overriding and Overloading
- override a method
- replace a base class method with a derived class
method having the same signature - overload a method
- create a new method having the same name as an
existing method in the same class or a base class
- new method must have a different signature
43Modifiers
44Overriding the foo( ) Method
- Class Base
- Overridable Sub foo()
- Console.WriteLine("foo in Base Class")
- End Sub
- End Class
- Class Derived Inherits Base
- Overrides Sub foo()
- WriteLine("foo in Derived Class")
- End Sub
- End Class
45Calling foo( )
- Late binding principle Common Language Runtime
looks up the object's type and executes the
appropriate version of foo( ) - Calls Derived.foo
- Dim obj As New Derived
- obj.foo()
- Calls Derived.foo
- Dim obj As Base New Derived
- obj.foo()
See Inheritance.Overriding
46Abstract Classes Methods
- Abstract Class
- declared with the MustInherit modifier
- You cannot create an instance of an abstract
class - Abstract Method
- declared with the MustOverride modifier
- prototype, with no implementation
47Example
- MustInherit Class Base
- MustOverride Sub foo()
- End Class
- Class Derived Inherits Base
- Overrides Sub foo()
- WriteLine("foo in Derived Class")
- End Sub
- End Class
48Abstract Employee Class
- (partial listing)
- MustInherit Class Employee
- Implements IComparable
- Sub New(ByVal empId As Integer, ByVal name As
String) - mEmpId empId
- mName name
- End Sub
- MustOverride ReadOnly Property GrossPay() As
Decimal - (etc.)
See Inheritance.AbstractEmployee
49Polymorphism
- Webster "having, occurring, or assuming various
forms, characters, or styles" - OOP base type's ability to reference various
derived types - Dim emp As Employee New SalariedEmployee(1001,
"Johnson, Cal", 57000)
50Polymorphism
- DoCalculations method accepts any type of
Employee - Sub DoCalculations(ByVal emp As Employee)
- WriteLine(emp.ToString() " " _
- FormatCurrency(emp.GrossPay) " - " _
- FormatCurrency(emp.CalculateTax) " " _
- FormatCurrency(emp.NetPay))
- End Sub
- Dim X As SalariedEmployee, Y as HourlyEmployee
- DoCalculations( X )
- DoCalculations( Y )
See Inheritance.Polymorphism
51Collections
52.NET Collection Classes
- Powerful set of utility classes for holding
objects - Automatic search, sort, insert, delete operations
- Alternative to relational database
- hierarchical data representation
53System.Collections Namespace
54HashTable Class
- Dictionary-type collection stores keys and their
associated values - optimized for quick storage and retrieval
- keys must be unique
- Implements IDictionary and ICollection interfaces
- ICollection
- Count property
- CopyTo method copies a collection into an Array
IDictionary
55IDictionary Interface
56Averages Example
- Create the Hashtable
- Dim averages As New Hashtable
- With averages
- .Add("Joe", 230.2)
- .Add("Dan", 330.2)
- .Add("Ann", 210.0)
- .Add("Bob", 430.2)
- .Add("Sam", 160.6)
- .Add("Jim", 200.7)
- End With
57Averages Example
- Look up an entry
- Dim obj As Object averages.Item("Dan")
- Contains
- If averages.Contains("Bob") Then ...
- ContainsKey
- If averages.ContainsKey("Bob") Then ...
58Averages Example
- Display the Keys collection
- Dim name As String
- For Each name In averages.Keys
- WriteLine(name)
- Next
- Display the Values collection
- Dim score As Single
- For Each score In averages.Values
- WriteLine(score)
- Next
59Averages Example
- Display the Entries collection
- Dim entry As DictionaryEntry
- For Each entry In averages
- WriteLine(CStr(entry.Key) "--gt"
CSng(entry.Value)) - Next
See Collections.HashTableEx
60Calling ContainsValue
- Class defining values must override Equals( )
- Example user collection
- Dim users As New Hashtable
- users.Add("joe","xxabc2")
- users.Add("sam","ieshfds")
- ContainsValue
- If averages.ContainsValue("xxabc2") Then ...
61SortedList Class
- Implements the IDictionary interface
- each entry is a DictionaryEntry object
- Maintains the keys in sorted order
- keys must be unique
- Example
- Dim list As New SortedList
- Dim emp As Employee
- emp New Employee(1001, "Jones, Dan")
- list.Add(emp.EmpId, emp)
- emp New Employee(3001, "Baker, Sam")
See Collections.SortedListEx
62Visual Inheritance
63Creating Derived Forms
- Visual Inheritance is the building of new forms
from existing ones - Useful Application
- create Master form with a standard appearance and
control set - custom forms can extend the Master form
- Creating a derived form in Visual Studio
- Right-click on project name select Add, select
Add Inherited Form
64Creating Derived Forms
- (continued)
- Select the base form in the Inheritance Picker
65BaseForm and Login Classes
- Visual Inheritance Hands-on Example
- File VisualInherit
66Scope of Controls
- Scope considerations
- make all controls in the form Protected
- Event handling
- if base class has no handler, you can create one
in the derived class - if base class has a handler, you have to do more
work - event handlers are never overridable
- event arrives at derived class first
67Handling a Click Event
68Delegates(optional topic)
69Delegates
- Declares a method type (including signature)
- Delegate variables usually point to methods
- Declare a delegate
- Delegate Sub Sub_NoParms()
- Declare a method of the same type
- Sub Hello()
- System.Console.WriteLine("Hello there")
- End Sub
70Delegates
- Assign the variable a method of the same type
- Dim deleg As Sub_NoParms
- deleg AddressOf Hello
- Invoke the method
- deleg.invoke()
71Indirect Method Calls
- Declare a delegate and two matching methods
- Delegate Sub Sub_OneString(ByVal parm As String)
- Sub ShowColor(ByVal color As String)
- System.Console.WriteLine("Color " color)
- End Sub
- Sub ShowFruit(ByVal fruit As String)
- System.Console.WriteLine("Fruit " fruit)
- End Sub
72Indirect Method Calls
- Create a method that calls any delegate
- Sub Call_a_proc(ByVal deleg As Sub_OneString, _
- ByVal parm As String)
- deleg.Invoke(parm)
- End Sub
- Call Call_a_proc
- Call_a_proc(AddressOf ShowColor, "Green")
- Call_a_proc(AddressOf ShowFruit, "Orange")
- Output
- Color Green
- Fruit Orange
73Key Terms
- abstract class
- abstract method
- base class
- collection
- comparator
- dictionary
- derived class
- downward cast
- enabling technology
- Enum
- Hashtable
- IComparable
- IComparer
- IDictionary
- interface
- overload
- override
- polymorphism
- reference type
- Reflection
- runtime type identification
- SortedList
- Structure
- TypeOf
- value equality
- value type
- visual inheritance
74The End