Download presentation
Presentation is loading. Please wait.
Published byDerrick McDonald Modified over 9 years ago
1
Dr. Azeddine Chikh IS444: Modern tools for applications development
2
Part 2. VB.NET reminder Chapter4: Problem Domain Class
3
Objectives In this lesson, you will: Learn VB.NET naming conventions Write a problem domain class definition Work with exceptions Implement generalization/specialization class hierarchy Understand and use interfaces Understand association relationships 3
4
4 VB.NET Naming Conventions Class names Start with a capital letter Examples: Student, Course Attribute names Begin with a lowercase character Subsequent words are capitalized Examples: address, phoneNo, studId Method names Begin with an uppercase character Subsequent words are capitalized Examples: GetPhoneNo, SetAddress, CalAver
5
Developing a PD Class Definition University system PD classes include Student Section Department Instructor Teaching LablectureTutorial PartTimeStudent Term Person Course * * * * * * * * 1 1 1 1 * 1
6
6 Class Definition Structure Structure of a class definition Public Class … … … … End Class Public Class Student ‘ represents KSU’s students Private studentId As String Private firstName As String Private lastName As String Private address As String Private phoneNo As String Private email As String Private dateOfBirth As Datetime Private entryDate As Datetime Private citizenship As String Private gpa As Single Private initLev As Byte
7
7 In OO systems, objects interact by one object sending a message to another object to invoke a method. Defining Methods
8
8 Methods : Accessor methods or Custom methods Methods are written using procedures : two types A Sub procedure does not return a value Sub ( ) End Sub A Function procedure returns a value Function ( ) As method statements Return End Function Defining Methods
9
9 Two types of accessor methods Get accessor methods or getters Public Function GetAttributeName ( ) As AttributeDatatype Return AttributeName End Function Public Function GetAddress ( ) As String Return address End Function Set accessor methods or setters Public Sub SetAttributeName ( ByVal paramterName As AttributeDatatype) AttributeName = paramterName End Sub Public Sub SetAddress ( ByVal astudAdd As String) address = astudAdd End Sub Defining Methods
10
10 Defining Properties A property Can be used to set and get attribute values Similar to a method, but appears as an attribute to a client. Public Property ( ) As Get Return End Get Set (ByVal As ) = End Set End Property Public Property StudentEmail ( ) As String Get Return email End Get Set (ByVal aEmail As String) email = aEmail End Set End Property
11
11 Creating an Instance Creating an instance of a class: Dim aStud As Student aStud= New Student ( ) Dim aStud As Student = New Student ( ) Attributes of the Student instance initially have no values Instance attributes can be populated by Setter methods aStud.SetEmail("mohamed@ccis.ksu.edu.sa") Properties aStud.email = “mohamed@ccis.ksu.edu.sa”
12
12 Creating an Instance Code to retrieve attribute values and display them: ' define variables to contain attribute values retrieved Dim aFN, aLN, aPhNo As String aFN = aStud.GetFirstName() aLN = aStud.GetLastName() aPhNo = aStud.GetPhoneNo() ' display the retrieved attribute values Console.WriteLine("The name is " + aFN) Console.WriteLine("The address is " + aLN) Console.WriteLine("The phone is " + aPhN)
13
13 Writing a Constructor Method Default constructor Created by VB.NET if the programmer does not write a constructor Does not do anything Consists of only a header and an End Sub statement Parameterized constructor Created by the programmer Can contain a parameter list to receive arguments that are used to populate the instance attributes during the instantiation process.
14
14 Writing a Constructor Method Parameterized constructor for Student Public Sub New(ByVal aFN As String, ByVal aLN As String) SetFirstName(aFN) SetLastName(aLN) ….. End Sub Alternative design: constructor assigns values directly to attribute variables instead of invoking setter methods Public Sub New(ByVal aFN As String, ByVal aLN As String) FirstName = aFN LastName = aLN …. End Sub Instantiation Example : Dim aStud as Student aStud = New Student (“Habib”, “Chikh”)
15
15 Writing a TellAboutSelf Method Good design: changes in one class (adding new attributes, and etc) should be insulate from outside classes (Clients) to reduce maintenance requirements especially when using getter methods. To accomplish this, a TellAboutSelf method can be used Can be invoked to retrieve all of the attribute values for an instance Places all the values in a String instance Returns the String instance to the invoking client Should have public accessibility Should be written as a Function procedure
16
16 Writing a TellAboutSelf Method TellAboutSelf method for Student 'TellAboutSelf method Public Function TellAboutSelf() As String Dim info As String info = “ID = " & GetIStudentId() & _"Name = " & GetFirstName() & GetLastName() &_ ", Nationality = " & GetCitizenship() &_ ", Address = " & GetAddress() &_ ", Phone No = " & GetPhoneNo() &_ ", Email address = " & GetEmail() &_ ", Date of birth = " & GetDateOfBirth() &_ ", Date of entry = " & GetEntryDate() &_ ", GPA= " & Getgpa() & _ ", Initial level = " & GetinitLev() Return info End Function Polymorphic methods Two methods with the same name, residing in different classes, that behave differently Example: TellAboutSelf methods for Student and Course classes
17
17 Testing a PD Class A tester class simulates the way a client might send messages For example: Tester class can invoke methods in the Student class definition Tester is the client and Student is the server Tester is the startup object for the project Main method begins execution when it is loaded Tester as module A console application is used to run it Tester as form (GUI object) A windows application is used to run it
18
18 Creating Custom Methods Registration method: A custom method Computes the registration fees for a student Fees range from 1000SR to 2000SR depending on the student initial level A Function procedure Will return a value: registration fee amount Has Public accessibility Can be invoked by any object Return data type: Single Will compute and return the student registration fee, a RS amount
19
19 Creating Custom Methods computing registration fee: Public Function Registration() As Single Dim fee As Single Select Case initLev Case 1 To 2 fee = 1000 Case 3 To 4 fee = 1200 Case 5 To 6 fee = 1400 Case 7 To 8 fee = 1600 Case Else fee = 2000 End Select Return fee End Function
20
20 Writing Class Variables and Methods Each instance has a copy of both Instance variables Class variables and methods Shared by all instances of the class: each instance does not have its own copy Declared using the keyword Shared Class variables are global variables on level of instances Private Shared numbOfStud As Integer = 0 Code added to the Student constructor for the numbOfStud 'increment shared attribute numbOfStud+= 1 Class methods can be called only using classes Public Shared Function GetNumbOfStud() As Integer Return numbOfStud End Function Note: You can call the class method by using an instance, because VB.Net replaces this instance by its class name.
21
21 Writing Overloaded Methods Method signature: Name and parameter list A class definition can contain several methods with the same name, as long as their parameter lists differ (with different signatures). VB.NET identifies a method by its signature, not only by its name Overloaded method: a method that has the same name as another method in the same class, but a different parameter list.
22
22 Overloading a Constructor Problem at KSU Most students of KSU are from KSA (Kingdom of Saudi Arabia) but a few are from other countries Current Student constructor requires 11 arguments: studentId, firstName, lastName, address, phoneNo, email, dateOfBirth, entryDate, citizenship, gpa, initLev Solution Write a second Student constructor that has only 10 parameters : studentId, firstName, lastName, address, phoneNo, email, dateOfBirth, entryDate, gpa, initLev Include statements to assign the default value of “KSA” to citizenship
23
23 Overloading a Constructor Constants can be used for the default citizenship value: Private Const DEFAULT_ citizenship As String = “KSA” Code for second constructor: Overloads keyword is not used with constructors Public Sub New(ByVal aStudId As String, ByVal aFN As String, ByVal aLN As String, ByVal aadd As String, ByVal aphNo As String, ByVal aemail As String, ByVal adatBirth As Datetime, ByVal aentDat As Datetime, ByVal agpa As Single, ByVal alev As Byte ) Me.New (aStudId, aFN, aLN, aadd, aphNo, aemail, adatBirth, aentDat, agpa, alev, DEFAULT_ citizenship) End Sub VB.NET determines which constructor to invoke by the argument list.
24
24 Overloading a Custom Method Problem at KSU University permits a discounted registration fee under certain conditions Solution A second version of the Registration method that accepts a value for the percentage discount Will overload the original Registration method Two Registration methods in Student, each with a different signature Original Registration has an empty parameter list Second Registration has a parameter variable named aDiscountPercent Public Overloads Function Registration (ByVal aDiscountPercent As Single) As Single Dim fee As Single = Me. Registration ( ) Dim discountFee As Single = fee * (100 - aDiscountPercent) / 100 Return discountFee End Function
25
25 Working with Exceptions An exception Used to notify the programmer of errors, problems, and other unusual conditions that may occur while the system is running. An instance of the Exception class or one of its subclasses. Try Used by the client Catch Used by the client Finally Used by the client End Try Used by the client Throw Used by the server
26
26 Data validation for initLev (Server side) InitLev value should be within the range of 1 through 10. SetInitLev method Data validation logic used to verify that initLev values are in the range of 1 - 10 Create and throw an exception instance if a value is outside the valid range Constant MAXIMUM_NUMBER_OF_TERMS to simplify future maintenance ( Private Const MAXIMUM_NUMBER_OF_TERMS As Integer = 10) Public Sub SetInitLev(ByVal ainitLev As Byte) If ainitLev MAXIMUM_NUMBER_OF_TERMS Then Dim ex As Exception ex = New Exception(“initial level not between 1 and " _ & MAXIMUM_NUMBER_OF_TERMS ) Throw ex Else initLev= ainitLev End If End Sub
27
27 Catching Exceptions (Client Side) If a method that might throw an exception is invoked, the invoking code must be prepared to catch the exception.NET CLR will terminate processing if an exception is thrown and not caught. Dim aStud As Student Try aStud = New Student (“2021/005“,”MOHAMED”, “Chikh”, “Tlemcen”, “46-76577”, “moh_chikh@ccis.ksu.edu.sa”, “09/02/2003”, “09/09/2021”, “ALG”, 80, 1) Console.WriteLine(aStud.TellAboutSelf()) Catch theException As Exception Console.WriteLine("An exception was caught: " & theException.ToString()) Finally Console.WriteLine("Finally block always executes") End Try
28
Implementing the Student generalization/specification hierarchy 28 Student class Stores information about a student studentId, firstName, lastName, dateOfBirth, citizenship, address, phoneNo, email, entryDate, gpa, initLev Parameterized constructor Accepts values for all N attributes Standard accessor methods N setter methods N getter methods TellAboutSelf method (overridable method)
29
29 Public Class Student (1/2) Private studentId As String Private firstName As String Private lastName As String Private address As String Private phoneNo As String Private email As String Private dateOfBirth As Datetime Private entryDate As Datetime Private citizenship As String Private gpa As Single Private initLev As Byte Public Sub New(ByVal aStudId As String, ByVal aFN As String, ByVal aLN As String, ByVal aadd As String, ByVal aphNo As String, ByVal aemail As String, ByVal adatBirth As Datetime, ByVal aentDat As Datetime, ByVal agpa As Single, ByVal alev As Byte, ByVal citizenship As Byte) *call setters SetFirstName(aFN) SetLastName(aLN) … End Sub
30
30 Public Class Student (2/2) ‘N setter methods ‘N getter methods Public Overridable Function TellAboutSelf() As String Dim info As String info = “ID = " & GetIStudentId() & _"Name = " & GetFirstName() & GetLastName() &_ ", Nationality = " & GetCitizenship() &_ ", Address = " & GetAddress() &_ ", Phone No = " & GetPhoneNo() &_ ", Email address = " & GetEmail() &_ ", Date of birth = " & GetDateOfBirth() &_ ", Date of entry = " & GetEntryDate() &_ ", General average = " & Getgpa() & _ ", Initial level = " & GetInitLev() Return info End Function
31
31 Using the Inherits Keyword to Create the PartTimeStudent Subclass Generalization/specialization hierarchy Superclass Includes attributes and methods that are common to specialized subclasses Student class Common (11 attributes and 22 accessor methods) Instances of the subclasses Inherit attributes and methods of the superclass Include additional attributes and methods PartTimeStudent Subclass 3 additional attributes: Company address Position Work phone Student PartTimeStudent
32
32 Inherits keyword Used in the class header to implement a subclass Indicates which class the new class is extending Example: Public Class PartTimeStudent Inherits Student PartTimeStudent constructor Accepts 14 parameters 11 for attributes defined in the Student superclass 3 for additional attributes defined in PartTimeStudent MyBase.New call (reusability) Used to set attributes for compAdd, position and wPhoneNo Must be the first statement in the constructor Using the Inherits Keyword to Create the PartTimeStudent Subclass
33
33 Understanding Abstract and Final Classes 1. Concrete class Class that can be instantiated. It may have subclasses. Examples Student PartTimeStudent 2. Abstract class Not intended to be instantiated Only used to extend into subclasses Used to facilitate reuse MustInherit keyword is used in class header to declare an abst class Example: Public MustInherit Class Teaching 3. Final class A class that cannot be extended Created for security purposes or efficiency Created using the NotInheritable keyword Example : Public NotInheritable Class Lab Inherits Teaching
34
34 Overriding a superclass method Method overriding Method in subclass will be invoked instead of method in the superclass if both methods have the same signature Allows the subclass to modify the behavior of the superclass Method overriding vs. method overloading Overloading Two or more methods in the same class have the same name but have different signatures. Overriding (in inheritance situation only) Methods in both the superclass and subclass have the same signature Ex: TellaboutSelf() is defined in both student & PartTimeStudent. Overridable keyword included in method header (in the super class).
35
35 Overriding and invoking a superclass method Sometimes the programmer needs to override a method by extending what the method does For example PartTimeStudent TellAboutSelf method invokes the superclass method using MyBase keyword, & Superclass method name Overrides included in subclass. Public Overrides Function tellAboutSelf() As String Return Mybase.tellAboutSelf() & compAdd & position & wPhoneNo End Function Polymorphism can be applied by inheritance Objects of different classes can respond to the same message in their own way Examples: tellAboutSelf( ) method in Student and PartTimeStudent
36
36 Understanding private versus protected access Declaring attributes as Private Other objects must use methods of the class to get or set values Ensures encapsulation and information hiding Limits the ability of an instance of a subclass to directly access attributes defined by the superclass Declaring attributes as Protected Values can be directly accessed by only their classes & the subclasses. Local variables Accessible only to statements within a method where it is declared Exists only as long as the method is executing Does not need to be declared as private, protected, friend, or public Methods Private methods Can only be invoked from a method within the class Cannot be invoked even by subclass methods Protected methods Can be invoked by a method in a subclass
37
37 Teaching Class Public MustInherit Class Teaching Private credHrs As Byte Private roomNo As String Public Sub New(ByVal aCredHrs As Byte, ByVal aRoomNo As String) setCredHrs(acredHrs ) setRoomNo(aroomNo) End Sub Public MustOverride Function calcLoad(ByVal acredHrs As Byte) As Single 'tellAboutSelf method 'Setters 'Getters End Class Lab Class Public Class Lab Inherits Teaching Private ProgLang As String Private CompConf As String … Public Overrides Function calcLoad(ByVal acredHrs As Byte) As Single Dim load As Byte load = acredHrs *2 Return load End Function End Class
38
38 Understanding and Using Interfaces An interface Defines abstract methods that must be implemented by classes that use the interface. Can be used to ensure that an instance has a defined set of methods. Component-based development Components interact in a system using a well-defined interfaces. Components might be built using a variety of technologies. Play an important role in developing component-based systems A VB.NET class Can inherit from only one superclass Can implement one or more interfaces Interfaces allow VB.NET mimics the multiple inheritance, which refers to the ability to inherit from more than one direct class.
39
39 Creating a VB.NET Interface Public Interface ITeachingInterface ' all Teaching classes must include calcLoad method Function calcLoad(ByVal acredHrs As Integer) As Single End Interface Public Class Lab Inherits Teaching Private ProgLang As String Private CompConf As String ….. Public Function calcLoad (ByVal acredHrs As Integer) As Single _ Implements ITeachingInterface.calcLoad, … Dim load As Byte load = acredHrs *2 Return load End Function End Class
40
40 Using Custom Exceptions Custom exception (An example of extending a built-in class) An exception written specifically for an application Exception is not abstract class (it is a concrete class) Defining CalcLoadException Created by defining a class that extends the Exception class Designed for use by the Lab class Thrown if credHrs is invalid.
41
41 Client Class (Form) Dim Lb as Lab …… Try Lb.calcLoad(10) Catch ……. Server Class (Lab ) …… CalcLoad Definition It may throw ex. If value is not valid. Custom Exception (CalcLoadException) 1 1 a CalcLoadException Instance
42
42 Public Class CalcLoadException Inherits Exception Dim theLab As Lab Dim nhrs As Byte Dim exceptionMessage As String Public Sub New(ByVal anhrs As Single, ByVal alab As Lab) MyBase.New("Calculate Load Exception") theLab= aLab nhrs = anhrs exceptionMessage = “the value: “ End Sub Public Overrides Function ToString() As String Return exceptionMessage & nhrs & “ is not valid for the lab” & theLab End Function End Class
43
43 Throwing a Custom Exception CalcLoad method A custom method defined in Lab class. Throws a CalcLoadException instance if credit hours is more than 5 Public Function CalcLoad (ByVal acredHrs As Integer) As Single Dim load As Byte If acredHrs <= 5 Then load = acredHrs *2 Return load Else Throws new CalcLoadException(acredHrs, Me) End if End Function End Sub Client Code Dim lb AS Lab Try lb.CalcLoad (6) Catch e1 AS CalcLoadException Messagebox.show(e1.toString() ) End Try
44
44 Understanding the Object Class and Inheritance Object class Extended by all classes in VB.NET Defines basic functionality that other classes need in VB.NET ToString method A method of the Object class Inherited by all classes By default, returns a string representation of the class name Overridden by other classes to provide more specific information Some other methods of the Object class The Default New constructor Equals GetType Others
45
45 Identifying Association Relationships on KSU’s Class Diagram Student Section Department Instructor Teaching LablectureTutorial PartTimeStudent Term Person Course * * * * * * * * 1 1 1 1 * 1
46
46 Identifying Association Relationships on KSU’s Class Diagram Association relationship can be shown also as: Aggregation relationship: Composition relationship: Teaching class ( Association class) Exists because of the relationship between Instructor and Course Shown as a class connected by a dashed line to an association between Instructor and Course To implement an association relationship in VB.NET Use a reference variable as an attribute of a class. It is a reference variable points to an actual instance. Though, you can invoke the methods of that instance using that attribute.
47
47 Associating students and departments: A one-to-many association relationship Association between Student and Department: 2 directions To implement one-to-one association relationship between between Student and Department A department reference variable If added as an attribute in the Student class, each Student instance can points to a Department instance and invoke the Department’s methods To implement one-to-many association relationship between Department and Student Requires that a Department instance have reference variables for more than one student Use an ArrayList in the Department class to hold many Student reference variables
48
48 ArrayList class Can be used to instantiate a container that can hold many reference variables Has methods which can be used to Add Student references Retrieve Student references Associating students and departments: A one-to-many association relationship
49
49 Introducing the Department Class Department class Four previous attributes An ID number AS String, A location AS String, A headAS String, A label AS String Fifth attribute Students : An ArrayList which implements the one-to-many association relationship, Ex: Private students as ArrayList Department class constructor Sets values for the four attributes Instantiates the new ArrayList Assigns the new ArrayList to the students attribute. Ex: students = New ArrayList( ) GetStudents Public Function GetStudents( ) As ArrayList Return students End Function AddStudent custom method : i nvoked by the Student AddStudToDep method Public Sub AddStudent( ByVal aStud As Student) students.Add(aStud) End Sub
50
50 Modifications to the Student class to implement the mandatory one-to-one association relationship TheDep attribute A Department reference variable : Private theDep As Department Accessor methods for the Department reference attribute GetDep() et SetDep() Modified constructor Expects a Department reference parameter Result: When a student is instantiated, it must be associated with a department (Mandatory Relation) Invokes the student’s AddStudToDep method which establishes the association in both directions by Public Sub AddStudToDep(ByVal aDep As Department) aDep.addStudent(Me) setDep(aDep) End Sub A TellAboutSelf method returns information about the student & the students’s department Public Function TellAboutSelf( ) As String Return “Attributes of Student” & theDep.TellAboutSelf( ) End Function Associating the Student Class with Department
51
51 Creating and using an association class – Teaching Teaching class An association class Teaching is an association relationShip between Instructor and Section but with attributes for credHrs & RoomNo Subclasses : Lab & Lecture &Tutorial Modifications to the Teaching class An Instructor reference attribute Private thesIns As Instructor A Section reference attribute Private theSec As Section Accessor methods Modifications to the Instructor class Modifications to the Section class ….
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.