VB Classes - 2 ISYS 573. Creating an Array of Objects Dim emps(2) As emp Dim i As Integer For i = 0 To emps.GetUpperBound(0) emps(i) = New emp() Next.

Slides:



Advertisements
Similar presentations
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Advertisements

Written by: Dr. JJ Shepherd
Creating Custom Controls. Overriding ToString Method Every class you create in VB.Net is derived from a built-in class named object. –Mscorlib/system/object.
Advanced Object Oriented Concepts Tonga Institute of Higher Education.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
Chapter 11: Implementing Inheritance and Association Visual Basic.NET Programming: From Problem Analysis to Program Design.
12-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
More about classes and objects Classes in Visual Basic.NET.
VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Creating Custom Controls ISYS 512/812. Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface.
VB.Net Loops.
1 Inheritance & Interface. 2 Why Inheritance? Common properties? Methods to send congratulations to Employees and Customers Public Sub SendCongratulationsE(ByVal.
VB Classes - 2 ISYS 573. Creating an Array of Objects Dim emps(2) As emp Dim i As Integer For i = 0 To emps.GetUpperBound(0) emps(i) = New emp() Next.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Advanced Object-Oriented Programming Features
Compunet Corporation1 Programming with Visual Basic.NET Inheritance Lecture # 10 Tariq Ibn Aziz.
Creating Custom Controls. Overriding ToString Method Every class you create in VB.Net is derived from a built-in class named object. –Mscorlib/system/object.
VB Classes BICS546. Adding a Class to a Project Project/Add Class Class will be saved in a.CLS file Steps: –Adding properties Declare Public variables.
Inheritance and User-Defined Controls. Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface.
VB.NET Classes ISYS 812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
VB Classes ISYS 512. Adding a Class to a Project Project/Add Class –*** MyClass is a VB keyword. Steps: –Adding properties Declare Public variables in.
VB.Net Loops. Loop FOR index – start TO end [STEP step] [statements] [EXIT FOR] NEXT index DO [{WHILE| UNTIL} condition] [statements] [EXIT DO] LOOP.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Object-Oriented Programming in Visual Basic.NET. Overview Defining Classes Creating and Destroying Objects Inheritance Interfaces Working with Classes.
Object-Oriented Programming: Inheritance
To define a class in Visual Basic.NET, you can follow this general procedure: 1. Add a class to the project. 2. Provide an appropriate file name for.
Inheritance Chapter 14. What is inheritance?  The ability to create a class from another class, the “parent” class, extending the functionality and state.
BASE CLASSES AND INHERITANCE CHAPTER 4. Engineer Class.
Module 7: Object-Oriented Programming in Visual Basic .NET
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Programming Pillars Introduction to Object- Oriented Programming.
Java Classes ISYS 350. Introduction to Classes Two basic uses of class: – 1. A class is a way to organize functions (methods) to perform calculations.
C#/Java Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the.
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.
Java Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the.
CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.
Object Oriented Software Development
Objects andVB Classes ISYS 350. What Is an Object? Objects are key to understanding object-oriented technology. There are many examples of real-world.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
Microsoft Visual Basic 2008 CHAPTER ELEVEN Multiple Classes and Inheritance.
VB Classes ISYS 512/812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Created by Alia Al-Abdulkarim 2008 Visual Basic Vs. Java.
C# Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the properties.
Objects andVB Classes ISYS 350. What Is an Object? Objects are key to understanding object-oriented technology. There are many examples of real-world.
C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties.
Object-Oriented Programming: Inheritance and Polymorphism.
Chapter 2 11/18/2015 © by Pearson Education, Inc. All Rights Reserved. Lect9 GC 2011.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
These materials where developed by Martin Schray
Object-Oriented Programming: Classes and Objects
Inheritance and Polymorphism
Microsoft Visual Basic 2005: Reloaded Second Edition
Object-Oriented Programming: Classes and Objects
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Inheritance
Chapter 11 – Object-Oriented Programming
Java Programming Language
1.الدوال Function 2.الاجراءاتSub Procedure 3.وحده نمطيه Add Module
IS437: Fall 2004 Instructor: Dr. Boris Jukic
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Inheritance
CIS 199 Final Review.
VB Classes ISYS 512.
Object-Oriented Programming: Inheritance
Presentation transcript:

VB Classes - 2 ISYS 573

Creating an Array of Objects Dim emps(2) As emp Dim i As Integer For i = 0 To emps.GetUpperBound(0) emps(i) = New emp() Next emps(0).Eid = "e1" emps(0).Ename = "peter" emps(0).salary = 5000

Implementing a 1:M Relationship With Object Array Public did As String Public dname As String Public emps(2) As Employee Public eid As String Public ename As String Public salary As Double Class Department Class Employee

Code Example Dim tempDep As New department() tempDep.did = "D1" tempDep.dname = "Accounting" tempDep.emps(0) = New emp() tempDep.emps(0).Eid = "E1" tempDep.emps(0).Ename = "Peter" MessageBox.Show(tempDep.emps(0).Ename)

Implementing a 1:M Relationship With ArrayList Public did As String Public dname As String Public emps As New ArrayList Public eid As String Public ename As String Public salary As Currency Class Department Class Employee

Example Public Class Dept Public did As String Public dname As String Public emps As New ArrayList Public Sub addemp(ByVal id As String, ByVal name As String) Dim e As New Emp e.eid = id e.ename = name emps.Add(e) End Sub End Class Public Class Emp Public eid As String Public ename As String End Class

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim test As New Dept test.did = "d1" test.dname = "MIS" test.addemp("e1", "peter") test.addemp("e2", "paul") MessageBox.Show(test.emps.Item(0).eid) MessageBox.Show(test.emps.Item(1).eid)

Problem with Using ArrayList to Model the Entity on the Many Side of the Relationship ArrayList can store different types of objects. Because the property is a collection, user may use collection’s Add method to add a object of different type. –Test.Emps.Add(“Other Type”)

Collection Class A collection class holds references for a series of objects created from the same class. –Create a hidden Private collection to hold data. –Create methods to simulate collection’s Add, Count, Items,RemoveAt, … etc. Example:

Public Class Dept Public did As String Public dname As String Public emps As New depEmps End Class Public Class Emp Public eid As String Public ename As String End Class Public Class depEmps Private hiddenList As New ArrayList Public Sub add(ByVal id As String, ByVal name As String) Dim e As New Emp e.eid = id e.ename = name hiddenList.Add(e) End Sub Public ReadOnly Property items() As ArrayList Get items = hiddenList End Get End Property Public ReadOnly Property count() Get count = hiddenList.Count End Get End Property End Class

Code Using the Collection Class Dim test As New Dept test.did = "d1" test.dname = "MIS" test.emps.add("e1", "peter") test.emps.add("e2", "paul") MessageBox.Show(test.emps.items(0).eid) MessageBox.Show(test.emps.items(1).eid)

What If We Only Allow Two Employees in Each Dept? Public Sub add(ByVal id As String, ByVal name As String) Dim e As New Emp e.eid = id e.ename = name Static eCount As Integer If eCOunt > 1 Then MessageBox.Show("too many") Else eCount += 1 hiddenList.Add(e) End If End Sub

How to implement the Remove method? How to implement the RemoveAt method?

Nested Classes VB.Net lets you nest class definitions: –Class Outer … Class Inner … End Class –End Class The inner class can be declared as: –Dim obj As New Outer.Inner

Public Class Emp Public Eid As String Public Ename As String Public salary As Double Public dependents As New deps() Public Class deps Private dcol As New arraylist Public Sub add(ByVal did As Integer, ByVal dname As String) Dim d As New dep() d.depID = did d.depName = dname dcol.Add(d) End Sub Public ReadOnly Property items() As ArrayList Get items = dcol End Get End Property Public ReadOnly Property count() Get count = dcol.Count End Get End Property End Class

Public Class dep Public depID As Integer Public depName As String End Class Dim test1 As New Emp() Dim test2 As dep test1.dependents.add(1, "peter") test1.dependents.add(2, "paul") Dim i As Integer For i = 1 To test1.dependents.count MessageBox.Show(test1.dependents.items(i).depname) Next For Each test2 In test1.dependents.items MessageBox.Show(test2.depID.ToString & test2.depName) Next Code using collection class

Store Objects in Storage Comma delimited file Database Serialization

Classes and Files Two files with 1:M relationship –Dept.dat, and Emp.dat Create a Dept class to model the relationship. Create a form that: –Display department Ids in a listbox. –Display selected department info and its employees in textboxes.

Serializing Classes Add a Serializable attribute: – Public Class Dept

Public Class Dept Public did As String Public dname As String Public emps As New depEmps End Class Public Class Emp Public eid As String Public ename As String End Class

Imports System.IO Imports System.Runtime.Serialization.Formatters.Binary Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim test As New Dept test.did = "d1" test.dname = "MIS" test.emps.add("e1", "peter") test.emps.add("e2", "paul") Dim fs As New FileStream("c:\testSerializing.txt", FileMode.Create) Dim bf As New BinaryFormatter bf.Serialize(fs, test) fs.Close() End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim fs As New FileStream("c:\testSerializing.txt", FileMode.Open) Dim testS As New Dept Dim bf As New BinaryFormatter testS = CType(bf.Deserialize(fs), Dept) TextBox1.Text = testS.did TextBox2.Text = testS.dname End Sub

Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class.

Inheritance Example Public Class Emp Public Eid As String Public Ename As String Public salary As Double Public Function tax() As Double tax = salary * 0.1 End Function End Class Public Class secretary Inherits Emp Public WordsPerMinute As Integer End Class

Overriding When a property or method in the base class is not adequate for a derived class, we can override the base class property or method by writing one with the same name in the derived class. The property or method in the base class must be declared with the Overridable keyword. The overridden property or method must be declared with the Overrides keyword. Note: Keywords Overridable and Overrides apply only to property procedure (not properties declared by public variables) or method.

Overriding a Method Public Class Emp Public Eid As String Public Ename As String Public salary As Double Public Overridable Function tax() As Double tax = salary * 0.1 End Function End Class Public Class secretary Inherits Emp Public WordsPerMinute As Integer Public Overrides Function tax() As Double If salary > 3000 Then tax = salary * 0.1 Else tax = salary * 0.05 End If End Function End Class

Overriding a Property Public Class Emp Public Eid As String Public Ename As String Private hiddenSal As Double Public Overridable Property salary() As Double Get salary = hiddenSal End Get Set(ByVal Value As Double) hiddenSal = Value End Set End Property End Class

Public Class secretary Inherits Emp Private sal As Double Public WordsPerMinute As Integer Public Overrides Property salary() As Double Get salary = sal End Get Set(ByVal Value As Double) If Value > 5000 Then sal = 5000 Else sal = Value End If End Set End Property End Class

MyBase The MyBase keyword refers to the base class. It is useful when you want to reference a field, property, or method of the base class.

Public Overridable Function tax() As Double tax = salary * 0.1 End Function Public Class secretary Inherits Emp Public WordsPerMinute As Integer Public Overrides Function tax() As Double If salary > 3000 Then tax = salary * 0.1 Else tax = salary * 0.05 End If End Function End Class Public Overrides Function tax() As Double If salary > 3000 Then tax = MyBase.tax Else tax = salary * 0.05 End If End Function Note: With MyBase, we can reuse the code in the base class.

The Scope of Class Properties and Methods Public: Available within its own class and to client code and subclasses. No restriction on access in the current or other projects. Private: Available only within its own class, not accessible from a derived class. Protected: Available only within its own class and derived subclasses, not available to client code. Friend: Available within its own class and to client code and subclasses, but only within the current project.

Abstract Classes (Virtual Classes) To prevent users from using your class as is and instead force them to inherit from it, you can create an abstract class. An abstract class cannot be instantiated, but is designed to be used only as a base class. An abstract class is declared with the MustInherit keyword: –Public MustInherit Class Person Abstract classes may have methods that are declared with the MustOverride keyword. Such methods are not implemented in the abstract class but must be implemented in any derived classes.

Abstract Class Example Public MustInherit Class clsEmp Public Eid As String Public Ename As String Public salary As Double MustOverride Function tax() As Double End Class Public Class clsEmpSecretary Inherits clsEmp Public Overrides Function tax() As Double If salary > 5000 Then tax = salary * 0.1 Else tax = salary * 0.1 End If End Function End Class

NonInheritable Classes (Sealed Classes) A class declared with the NotInheritable keyword can be instantiated but cannot be subclassed: –Public NotInheritable Class Emp Use NotInheritable when you want others to be able to use your class but not base their own classes on it.

Base Class and Derived Class Constructors It is possible for both a base class and a derived class to have constructors. When an instance of the derived class is created, the base class constructor is called first, and then the derived class constructor is called.

Comparing Object Variables with the Is Operator Multiple object variables can reference the same object. To determine whether two object variables reference the same object, use the Is operator, not =. –Dim emp1 as new emp() –Dim emp2 as emp –Emp2 = emp1 –If emp2 Is emp1 Then Msgbox(“Same object”) –End if

Exception Exceptions signal errors or unexpected events that occur while an application is running. An error handler is a section of code that intercepts and responds to exceptions.

Structured Error Handling Try result = Val(TextBox1.Text) / Val(TextBox2.Text) TextBox3.Text = result.ToString Catch except As InvalidCastException MessageBox.Show(except.Message) Catch except As DivideByZeroException MessageBox.Show(except.Message) Catch except As Exception 'Handle everything else MessageBox.Show(except.Message) Finally MessageBox.Show("I get exdecuted, no matter what") End Try

User-Defined Application Exceptions System.ApplicationException Throw –Throw New ApplicationException("Test exception") Use Try block to catch the excaption –Try Statements –Catch err ApplicationException MessageBox.Show(err.Message) –End Try

Application Exception Example Public Class emp Public SSN As String Public Ename As String Public DateHired As Date Private hiddenJobCode As Long Public Property JobCode() Set(ByVal Value) If Value 4 Then Throw New ApplicationException("Invalide JobCode") Else hiddenJobCode = Value End If End Set Get JobCode = hiddenJobCode End Get End Property End Class

Catch Application Exception Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim myEmp As New emp() Try myEmp.JobCode = TextBox1.Text MessageBox.Show(myEmp.JobCode) Catch err As ApplicationException MessageBox.Show(err.Message) TextBox1.Focus() End Try End Sub

User-Defined Exception Class Public Class JobCodeException Inherits System.ApplicationException Sub New(ByVal strMessage As String) MyBase.New(strMessage) End Sub End Class

Using User-Defined Exception in Class Private hiddenJobCode As Long Public Property JobCode() Set(ByVal Value) If Value 4 Then Throw New JobCodeException("Invalide JobCode") Else hiddenJobCode = Value End If End Set Get JobCode = hiddenJobCode End Get

Using User-Defined Exception in Program Dim myEmp As New Emp() Try myEmp.Eid = TextBox1.Text myEmp.Ename = TextBox2.Text myEmp.salary = CDbl(TextBox3.Text) myEmp.JobCode = TextBox4.Text Catch err As JobCodeException MessageBox.Show(err.Message) TextBox4.Focus() TextBox4.SelectAll() End Try