Learning VB.Net. Tutorial 19 Classes and Inheritance

Similar documents
Learning VB.Net. Tutorial 17 Classes

Learning VB.Net. Tutorial 15 Structures

Learning VB.Net. Tutorial 16 Modules

Learning VB.Net. Tutorial 10 Collections

Tutorial 03 understanding controls : buttons, text boxes

Database Tutorials

Learning VB.Net. Tutorial 11 Functions

Database Tutorials

IMS1906: Business Software Fundamentals Tutorial exercises Week 5: Variables and Constants

FOR 240 Homework Assignment 4 Using DBGridView and Other VB Controls to Manipulate Database Introduction to Computing in Natural Resources

Revision for Final Examination (Second Semester) Grade 9

C4.3, 4 Lab: Conditionals - Select Statement and Additional Input Controls Solutions

Lecture 10 OOP and VB.Net

CALIFORNIA STATE UNIVERSITY, SACRAMENTO College of Business Administration. MIS 15 Introduction to Business Programming. Programming Assignment 3 (P3)

Level 3 Computing Year 2 Lecturer: Phil Smith

Objectives. After completing this topic, the students will: Understand of the concept of polymorphism Know on How to implement 2 types of polymorphism

DEVELOPING OBJECT ORIENTED APPLICATIONS

1. Create your First VB.Net Program Hello World

How to Validate DataGridView Input

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES

In this tutorial we will create a simple calculator to Add/Subtract/Multiply and Divide two numbers and show a simple message box result.

How to use data sources with databases (part 1)

PROGRAMMING ASSIGNMENT: MOVIE QUIZ

Lab 3 The High-Low Game

Mr.Khaled Anwar ( )

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

Public Class ClassName (naming: CPoint)

C16 Visual Basic Net Programming

DRAWING AND MOVING IMAGES

ADO.NET 2.0. database programming with

The New Brew-CQ Synchronous Sockets and Threading

To enter the number in decimals Label 1 To show total. Text:...

I101/B100 Problem Solving with Computers

Section 7 The BASIC Language II

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

MATFOR In Visual Basic

MapWindow Plug-in Development

Year 12 : Visual Basic Tutorial.

7. Inheritance & Polymorphism. Not reinventing the wheel

11. Persistence. The use of files, streams and serialization for storing object model data

Repetition Structures

Equality for Abstract Data Types

Else. End If End Sub End Class. PDF created with pdffactory trial version

Design Of Human Computer Interfaces Assignment 1- Hello World. Compliance Report

Procedures (Subroutines) and Functions

Level 3 Computing Year 1 Lecturer: Phil Smith

How to work with data sources and datasets

Lab 4: Adding a Windows User-Interface

DO NOT COPY AMIT PHOTOSTUDIO

VISUAL BASIC 2005 EXPRESS: NOW PLAYING

VISUAL BASIC PROGRAMMING (44) Technical Task KEY. Regional 2013 TOTAL POINTS (485)

CS708 Lecture Notes. Visual Basic.NET Object-Oriented Programming. Implementing Client/Server Architectures. Part (I of?) (Lecture Notes 5A)

My first game. 'function which adds objects with bug tag to bugarray array. Saturday, November 23, :06 AM

Inheritance and Polymorphism

CS608 Lecture Notes. Visual Basic.NET Programming. Object-Oriented Programming Inheritance (Part II) (Part II of II) (Lecture Notes 3B)

IOS Plus Trade - Web Services Version 4 Walkthrough

IRESS Depth - Web Services Version 4 Walkthrough Visual Basic 2008 sample to retrieve IRESS Depth information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

LAMPIRAN A: Listing Program

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Form Adapter Example. DRAFT Document ID : Form_Adapter.PDF Author : Michele Harris Version : 1.1 Date :

Herefordshire College of Technology Centre Edexcel BTEC Level 3 Extended Diploma in Information Technology (Assignment 1 of 3)

Overview of the EMF Refresher Webinar Series. EMF Resources

Microsoft Visual Basic 2005: Reloaded

Language Fundamentals

Chapter 2 Exploration of a Visual Basic.Net Application

CS18000: Problem Solving And Object-Oriented Programming

UPDATING DATA WITH.NET CONTROLS AND A PROBINDINGSOURCE

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

CS 1110, LAB 1: PYTHON EXPRESSIONS.

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

OVERLOADING METHODS AND CONSTRUCTORS: The Ball Class

This PDF was generated in real-time using DynamicPDF; Generator for.net.

VBA Handout. References, tutorials, books. Code basics. Conditional statements. Dim myvar As <Type >

EXAMGOOD QUESTION & ANSWER. Accurate study guides High passing rate! Exam Good provides update free of charge in one year!

Interacting with External Applications

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Visual Basic 2008 The programming part

Chapter. Web Applications

Super-Classes and sub-classes

Function: function procedures and sub procedures share the same characteristics, with

10Tec igrid for.net 6.0 What's New in the Release

โปรแกรมช วยทดสอบหม อแปลงกระแส

MITOCW watch?v=0jljzrnhwoi

Create a custom tab using Visual Basic

Welcome To VTL Course

Running the Altair SIMH from.net programs

Lab 6: Making a program persistent

S.2 Computer Literacy Question-Answer Book

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University

Instructions for Crossword Assignment CS130

Module 4: Data Types and Variables

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Private Sub Cours_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Comp-304 : Object-Oriented Design What does it mean to be Object Oriented?

Upgrading Applications

U:\Book\Book_09.doc Multilanguage Object Programming

Python for Non-programmers

CPSC 217 Assignment 3

Transcription:

Learning VB.Net Tutorial 19 Classes and Inheritance Hello everyone welcome to vb.net tutorials. These are going to be very basic tutorials about using the language to create simple applications, hope you enjoy it. If you have any notes about it, please send them to notes@mka-soft.com I will be happy to answer them. Finally if you find these tutorials are useful, it would be nice from you to send a small donation via PayPal to donation@mka-soft.com. Tutorial posted on 2010-May-17.

Classes and Inheritance In the previous two tutorials, the definition of classes, methods, and their initialization is discussed. This tutorial is about how to perform inheritance. The same example used in the last tutorial is being used here as well. In many cases you want to take an existing class and extend its functionality. In our previous example the class ContactList has ContatArr() which is an array used to store the contacts, and the counter C which is used to tell how many elements we are using in the array. It also has methods to add a contact, remove a contact, and display the contacts in a DataGridView. What we want here is to create a new class that has the same methods and properties as ContactList, and also has a Sort method which allows you to sort the contacts by name. To do so simply add another class to your project, and call it ContactsWithSort. The first line of code in the class should be: Inherits ContactList The keyword Inherits here tells the complier that the class has behave in the same way as ContactList. In other words it is like copying the code of ContactList and pasting it to the new class (for now you can think about it like this, it makes things easier). Now let us try to add the new method to the class Public Sub Sort() ' this class has another method called sort. Dim F As Boolean Dim Contact As ContactInfo Do F = False For I = 0 To C - 2 If ContactArr(I).Name > ContactArr(I + 1).Name Then F = True Contact = ContactArr(I) ContactArr(I) = ContactArr(I + 1) ContactArr(I + 1) = Contact Loop While F Now if you try to run the program (even though you did not use the Sort method or the new class itself) you will get an error. The error is for using C and ContactArr. The error says that these variables are private. This brings up the issue of the accessibility of variables. When you define a variable in a class you can set its accessibility level to the following:

Public : this means that the variable can be access inside or outside the class. Private: this means that the variable can be accessed only inside the original class it is created in. Protected: this means that the variable can be accessed only in the class and all inherited classes. So let us check this using the following example: Public Class test Dim A As Integer Private B As Integer Public C As Integer Protected D As Integer Public Sub SetA(ByVal I As Integer) A = I Public Sub SetB(ByVal I As Integer) B = I Public Sub SetC(ByVal I As Integer) C = I Public Sub SetD(ByVal I As Integer) D = I In the example, A is treated as private. So if you add this method to the class: Public Sub SetA(ByVal I As Integer) A = I It works perfectly fine. However, if you add the following code into a form or module: Q.A = 10 This would trigger an error because A should only be accessed from within the class. Now let us check B which is private. If this is a method in the class, then it works. Public Sub SetB(ByVal I As Integer) B = I But if you add the following code into any place other than the class test, you get an error. Q.B = 10 So it works exactly like private. let us try to work with C which is Public.

Public Sub SetC(ByVal I As Integer) C = I This obviously works fine since it is in the same class (test). If you write the following code in any other place other than the class test, then it works perfectly fine. Q.C = 10 This works because the variable C here is public which means it can be accessed from any other place. Now let us check the last one D which is protected. The method within the class again has no problem Public Sub SetD(ByVal I As Integer) D = I If you want to access the variable D from outside the class it is treated like private, but it has some special treatment, which we will see later. Q.D = 10 So this triggers an error. Now let us go back to our example and see why we can t access the variable C and ContactArr. We used (Dim) for these two which means they are treated like private. As we have seen before that private variables in a class can not be accessed from outside the class itself. So we want to make them accessible. Making these variables public means that they will be accessed from any part of the project, which is not a good idea. If you change these variables visibility to protected, then the classes inherited from them will be able to access these. An access from any other location is denied. To test this try to create a class test2 inherited from test. Public Class test2 Inherits test Public Sub SetAll() A = 10 ' error B = 20 ' error C = 30 ' correct D = 40 ' correct Here A is not accessible in this class simply because it is private in the original class. B is the same so it causes the same problem. C is public in class test, so it is accessible here and everywhere else. D is protected so it is accessible in test2. The table below summarizes how these work:

Accessibility Base Class Inherited Class Outside the Class Dim Accessible Not Accessible Not Accessible Private Accessible Not Accessible Not Accessible Public Accessible Accessible Accessible Protected Accessible Accessible Not Accessible So going back to our example, set each of C and ContactArr in ContactList class to protected. You will see the code now is correct., modify the object in the form to use the new class: Dim OBJ As ContactsWithSort And modify the code of initialization of OBJ in the load event of the form: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load OBJ = New ContactsWithSort() Finally, add a menu item to sort the contacts, and write the following in the event handler: OBJ.sort() Run the code check it out. Below is the full code of the ContactList class: Public Class ContactList Protected ContactArr() As ContactInfo Protected C As Integer Public Sub AddNewContact() C = C + 1 ContactArr(C - 1) = New ContactInfo ContactArr(C - 1).ReadContactInfo() ' the array of object, all elements points to nothing ' the number of objects in the array ' the number of objects increases by one ' create the object ' read the information Public Sub RemoveContact(ByVal Name As String) ' search for the contact For I = 0 To C - 1 If ContactArr(I).Name = Name Then ' next remove the contact from the array by shifting the other objects Dim J As Integer For J = I + 1 To 999 ContactArr(J - 1) = ContactArr(J) ' the number of elements reduces by one C = C - 1 ' exit the block Exit Sub Public Sub FillDGV(ByVal DGV As DataGridView)

' clear the data grid view DGV.Rows.Clear() ' loop over all the contacts For I = 0 To C - 1 ' add contact information DGV.Rows.Add(ContactArr(I).Name, ContactArr(I).Address, ContactArr(I).Tel) Public Sub New() ' first constructor, set the number of elements to zero, and set array size to 1000 C = 0 ReDim ContactArr(0 To 999) Public Sub New(ByVal NoOfReads As Integer) ' second constructor, set number of elements to zero, and set array size to 1000 C = 0 ReDim ContactArr(0 To 999) ' add the contacts For I = 0 To NoOfReads - 1 Me.AddNewContact() Protected Overrides Sub Finalize() ' this is how to terminate a class For I = 0 To C - 1 ContactArr(I) = Nothing MyBase.Finalize() is the code for the ContactsWithSort class Public Class ContactsWithSort Inherits ContactList ' this tells the compiler that this class has the same behaviour of ContactList Public Sub Sort() ' this class has another method called sort. Dim F As Boolean Dim Contact As ContactInfo Do F = False For I = 0 To C - 2 If ContactArr(I).Name > ContactArr(I + 1).Name Then F = True Contact = ContactArr(I) ContactArr(I) = ContactArr(I + 1) ContactArr(I + 1) = Contact Loop While F And finally the code of the form:

Public Class Form1 Dim OBJ As ContactsWithSort Private Sub AddToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddToolStripMenuItem.Click OBJ.AddNewContact() Private Sub RemoveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveToolStripMenuItem.Click ' check if no rows are selected, if so no need to execute further code, just exit the subroutine If DGV.SelectedRows.Count = 0 Then Exit Sub Dim N As String ' get the selected name, it is the first column (cell zero) N = DGV.SelectedRows(0).Cells(0).Value OBJ.RemoveContact(N) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load OBJ = New ContactsWithSort() Private Sub SortToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortToolStripMenuItem.Click OBJ.sort() The rest of the files don t need modification, they are the same. So as you can see inheritance allows us to extend the functionality of an existing class, and add some features to them. So this is all for today. If you need the source file, you can get it from the web site. If you have notes about this tutorial, email me at: notes@mka-soft.com. Thanks. mkaatr