Oops

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Deccansoft Software Services

Agenda

OOPs Chapter-4

1. Learning about Class, Object, Component, Encapsulation, Inheritance, Polymorphism & Object Creation and Instantiation 2. Understanding OOPs concept through an example. Table of Contents O VERVIEW W ORKING WITH M ETHODS W ORKING WITH O BJECT P ROPERTIES C ONSTRUCTORS AND D ESTRUCTORS D ESTRUCTOR W ORKING WITH STATIC M EMBERS 2 8 10 14 16 17

Deccansoft Software Services

OOPs Chapter-4

Overview
Class: A class is a template / skeleton / blueprint for creating an object. Object: An Object is an entity that has properties for validations, methods for functionality and events for depicting the change of state. Every object has the data and behavior with which they are differed. Data associated at any given instance of time is the state of an object. Component: A ready to use third party object can be called as a Component. It can be replaced without any changes in the application. A component is generally used by a programmer as an object. An application can be called as a collection of related objects exchanging messages with each other. Loosely coupled objects are better than tightly coupled objects i.e. the lesser the information given to other objects the better it is as the objects are loosely coupled the dependencies are less and stronger security. Every object oriented language should have three features: Encapsulation Inheritance Polymorphism

Encapsulation: Binding of data and behavior i.e. functionality of an object within a secured and controlled environment is encapsulation. Inheritance: The Process of acquiring the existing functionality of the parent and with new added features and functionality by a child object is called inheritance. The advantages of inheritance are Generalization, Extensibility and Reusability. For example: A calculator is a generalized form of mathematical operations where as a Scientific calculator is an Extended and Specific form. Polymorphism: An object in different forms and in each form it exhibits the same functionality but implemented in different ways. For example: A man who knows more than one language can speak any language he knows. Here the functionality is speech and person is the object. A faculty can take a form of Java Faculty or MSNET faculty and in both the forms he teaches, but what he teaches differs. Here functionality is to teach and faculty is the object.

Deccansoft Software Services


Object Creation and Instantiation

OOPs Chapter-4

In MS.NET when an object is created there is no way to get the address of an object. Only the reference to the object is given through which we can access the members of the class for a given object. When an object is created all the variables (value/ reference types) are allocated the memory in heap as a single unit and default values are set to them based on their data types. Account Example: Steps to create an Account Application: 1. Create a new project (File New Project). Name: Account Application, Project Type: C#, Template: Windows Application 2. 3. View Solution Explorer, Right Click on Project Add Class and name it as Account To class, add the following code: Creating Account Class using System; using System.Text; using System.Windows.Forms; namespace AccountApplication { class Account { public int Id; public String Name; public Decimal Balance; public Account() { MessageBox.Show("Object Created"); } ~Account() { MessageBox.Show("Object Destroyed"); } } } Code: 4.1 C# Creating Account Class Public Class Account Public Id As Integer Public Name As String Public Balance As Decimal Shared Sub New() MessageBox.Show("Object Created") End Sub Protected Overrides Sub Finalize() MessageBox.Show("Object Destroyed") End Sub End Class Code: 4.1 VB

Deccansoft Software Services


Explanation: Account a;

OOPs Chapter-4

a is a reference variable of type Account. Note: a is not an object of type Account. a = new Account();

Creates an object of type Account (allocating memory on heap to every member of the Account class) and its reference is assigned to a. Every member allocated memory is set to its default value based on the data type. The value of the reference variable is reference to an object on heap. 4. Account a; 'Declaration a1 = new Account(); 'Initialization In the Account Application, Change the name of the Form, Form1 to AccountForm and design the following GUI 5. 6. Fig: 4.1 For every control on the form set Text and Name properties. In Design View, double click on every button to generate event handlers in Code View of the Form

Deccansoft Software Services

OOPs Chapter-4

Explanation a.Id = 1; The above statement can be read as: Id menber of an object of type Account referenced by a is set to 1. Note: If a reference variable is not intialized i.e referring to null, then trying to access any member using it will throw a runtime exception i.e. NullReferenceException. Account a1; a1 = a //Copies the value of a (reference to the object) into a1 and thus both a1 and a refers to the same object. Note: One Object can have many references but one reference variable cannot refer to many objects. 7. Add the following code to the Account Form i.e. Handle all the buttons Click event (Double click on button in design view) Account Form Code using System; using System.Text; using System.Windows.Forms; namespace AccountApplication { public partial class AccountForm : Form { Account a; public Form1() { InitializeComponent(); } private void btnCreate_Click(object sender, EventArgs e) { a = new Account(); } private void btnGet_Click(object sender, EventArgs e) { txtId.Text = a.Id.ToString(); txtName.Text = a.Name; txtBalance.Text = a.Balance.ToString(); } private void btnClear_Click(object sender, EventArgs e) { txtId.Text = ""; txtName.Text = ""; txtBalance.Text = ""; } private void btnSet_Click(object sender, EventArgs e) { a.Id = int.Parse(txtId.Text); a.Name = txtName.Text; a.Balance = decimal.Parse(txtBalance.Text); } private void btnDestroy_Click(object sender, EventArgs e) { a = null;

Deccansoft Software Services


} private void btnGC_Click(object sender, EventArgs e) { GC.Collect(); } private void btnTemp_Click(object sender, EventArgs e) { Account a1 = new Account(); a = a1; } private void btnGetgeneration_Click(object sender, EventArgs e) { MessageBox.Show(GC.GetGeneration(a).ToString()); } } } Code: 4.2 C#

OOPs Chapter-4

Account Form Code Public Class AccountForm Dim a As Account Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click Dim a As New Account End Sub Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click txtId.Text = a.Id.ToString() txtName.Text = a.Name txtBalance.Text = a.Balance.ToString() End Sub Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click txtId.Text = "" txtName.Text = "" txtBalance.Text = "" End Sub Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSet.Click a.Id = Integer.Parse(txtId.Text) a.Name = txtName.Text a.Balance = Decimal.Parse(txtBalance.Text) End Sub Private Sub btnDestroy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDestroy.Click a = Nothing End Sub

Deccansoft Software Services

OOPs Chapter-4

Private Sub btnGC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGC.Click GC.Collect() End Sub Private Sub btnTemp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTemp.Click Dim a1 As New Account a = a1 End Sub Private Sub btnGetGeneration_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetGeneration.Click MessageBox.Show(GC.GetGeneration(a).ToString()) End Sub End Class Code: 4.2 VB

Deccansoft Software Services

OOPs Chapter-4

Working with Methods


The methods of the object are used to describe the functionality / behavior. Note: An instance method of a class is always invoked using a reference to an object. While writing a method in a class do not set to it any data as parameter or return type, anything which is already the data member in the same class. In a method this(CS) is reference to the current object on which the method is invoked. If parameter/local variable and data member of a class have same name, the local variable takes the precedence over data member and if data member has to accessed in such a method then this (CS) can be used. The class should be always programmed in such a way that, its not specific to any particular type of application so that the same class can reused in different applications / environment. For example, dont use in class functionality like MsgBox or Console.WriteLine or Button or Label or TextBox etc. Whenever any of the business rules of an object or the integrity of the property or a method is violated, it should respond by throwing a runtime exception. For example in the above method Withdraw( ) we are checking for balance to be a minimum of 500, if violated an exception is raised. Recommendation: A method name should start with uppercase and parameters should use camel notation. 8. In the Account Class add the following deposit and withdraw method. Adding Deposit and Withdraw methods Public Sub Deposit(ByVal amount As Decimal) Me.Balance += amount End Sub Public Sub Withdraw(ByVal amount As Decimal) If Me.Balance - amount < 500 Then Throw New ApplicationException("Insufficient Balance") Else Me.Balance -= amount End If End Sub Code: 4.3 VB

Deccansoft Software Services


Adding Deposit and Withdraw methods public void Deposit(decimal amount) { this.Balance += amount; } public void Withdraw(decimal amount) { if (this.Balance - amount < 500) throw new ApplicationException("Insufficient Balance"); else this.Balance -= amount; } Code: 4.3 C# 9.

OOPs Chapter-4

Add Deposit (btnDeposit) and Withdraw (btnWithdraw) buttons and Amount (txtAmount) textbox to the AccountForm. Add the following code to the event handler of the btnDeposit and btnWithdraw. Handling Withdraw and Deposit events Private Sub btnWithdraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWithdraw.Click a.Withdraw(Decimal.Parse(txtAmount.Text)) End Sub Private Sub btnDeposit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeposit.Click a.Deposit(Decimal.Parse(txtAmount.Text)) End Sub Code: 4.4 VB

Handling Withdraw and Deposit events private void btnDeposit_Click(object sender, EventArgs e) { a.Deposit(decimal.Parse(txtAmount.Text)); } private void btnWithdraw_Click(object sender, EventArgs e) { a.Withdraw(decimal.Parse(txtAmount.Text)); } Code: 4.4 C#

Deccansoft Software Services

OOPs Chapter-4

Working with Object Properties


A Property encapsulates a field member of the same class, so that the field member is not freely accessible outside the class and the required validation/restriction can be put over it. A property is made of two blocks i.e. Get and Set. Get block is invoked when the property is used on RHS and Set block is invoked when the property is used on LHS. A property procedure doesnt hold any data by itself instead it depends on some private field member of the class. A Set block can validate the Value before it is assigned to the field member of the class being encapsulated by the property. Similarly the field member can be validated before its value is returned in the Get block. Using a property the field member can be restricted with either ReadOnly or WriteOnly access. A class which has all its field members as Private and if required restricted access to these members is given using Public Properties is called Fully Encapsulated Class. Syntax in C#: Private <Datatype> _<propertyname>; public <Datatype> <PropertyName> { [private] get { return _<propertyname>; } [private] set { _<propertyname> = value; } } 10. Add the properties for Name, Balance and Id with following conditions: Balance should be ReadOnly. Name should accept greater or equal to and 5 characters and less than or equal to 20 characters only Id should be set only once.

Edit the code in the Account Class as below: Adding properties Private _Id As Integer Private _Name As String Private _Balance As Decimal Private idAlreadySet As Boolean Public Property Id As Integer Get Return _Id End Get

10

Deccansoft Software Services

OOPs Chapter-4

Set(ByVal value As Integer) If (idAlreadySet) Then Throw New ApplicationException("Id is already set") End If _Id = value idAlreadySet = True End Set End Property Public Property Name As String Get Return _Name End Get Set(ByVal value As String) If (value.Length > 8) Then Throw New ApplicationException("Name cannot be greater than 8 characters") End If _Name = value End Set End Property Public ReadOnly Property Balance As Decimal Get Return _Balance End Get End Property Public Sub Deposit(ByVal amount As Decimal) Me._Balance += amount End Sub Public Sub Withdraw(ByVal amount As Decimal) If Me.Balance - amount < 500 Then Throw New ApplicationException("Insufficient Balance") Else Me._Balance -= amount End If End Sub Code: 4.5 VB Adding properties private int _Id; private String _Name; private Decimal _Balance; public decimal Balance { get { return _Balance; } } public String Name { get { return _Name;

11

Deccansoft Software Services

OOPs Chapter-4

11.

} set { if (value.Length > 8) throw new ApplicationException("Name cannot be > 8 characters"); _Name = value; } } private bool idAlreadySet; public int Id { get { return _Id; } set { if (idAlreadySet) throw new ApplicationException("Id is already set"); _Id = value; idAlreadySet = true; } } public void Deposit(decimal amount) { this._Balance += amount; } public void Withdraw(decimal amount) { if (this.Balance - amount < 500) throw new ApplicationException("Insufficient Balance"); else this._Balance -= amount; } Code: 4.5 C# In btnSet_Click of AccountForm

replace a.Balance = Decimal.Parse(txtBalance.text) with a.Deposit(decimal.Parse(txtBalance.Text)) To assign the values to an object Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSet.Click a.Id = Integer.Parse(txtId.Text) a.Name = txtName.Text a.Deposit(Decimal.Parse(txtBalance.Text)) End Sub Code: 4.6 VB

12

Deccansoft Software Services


To assign the values to an object private void btnSet_Click(object sender, EventArgs e) { a.Id = int.Parse(txtId.Text); a.Name = txtName.Text; a.Deposit(decimal.Parse(txtBalance.Text)); } Code: 4.6 C#

OOPs Chapter-4

13

Deccansoft Software Services

OOPs Chapter-4

Constructors and Destructors


A constructor is a member method of a class which is automatically executed / called as soon as the object of that class is created and thus it is ideally used for initializing the field members of the object. 1. 2. A constructor has same name as the class and doesnt have a return type not even void. A constructor without a parameter is called default constructor and the one with parameters is called as Parameterized constructor. 3. If a class doesnt have any form of constructor, a public default constructor is automatically added to it by the language compiler. 4. Copy Constructor is used to create a new object by duplicating the state of an existing object and this is done by copying the data members of existing object in new object data members. Syntax in C#: <Class name>() { //default constructor } <Class name>(<datatype> p1, ) { //parameterized constructor } <Class name>(<Class Name> <parname>) : this(. . .) { //copy constructor } 12. Add the Following code to the Account Class Adding parameterized constructors Public Sub New() End Sub Public Sub New(ByVal id As Integer, ByVal name As String, ByVal balance As Decimal) Me.Id = id Me.Name = name Me._Balance = balance End Sub Public Sub New(ByVal a As Account) Me.New(a.Id, a.Name, a.Balance) 'Me.Id = Id 'Me.Name = Name 'Me._Balance = Balance End Sub Code: 4.7 VB

14

Deccansoft Software Services


Adding parameterized constructors public Account() { } public Account(int id, String name, decimal balance) : this() { this.Id = id; this.Name = name; this._Balance = balance; } public Account(Account a) : this(a.Id, a.Name, a.Balance) { //this.Id = a.Id; //this.Name = a.Name; //this._Balance = a.Balance; } Code: 4.7 C# 13. In AccountForm make the following Changes:

OOPs Chapter-4

Changes in click event of Create Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click Dim id As Integer = Integer.Parse(txtId.Text) Dim name As String = txtName.Text Dim initialBalance As Decimal = Decimal.Parse(txtBalance.Text) Dim a As New Account(id, name, initialBalance) End Sub Code: 4.8 VB Changes in click event of Create private void btnCreate_Click(object sender, EventArgs e) { int id = int.Parse(txtId.Text); string name = txtName.Text; decimal initialBalance = decimal.Parse(txtBalance.Text); a = new Account(id,name, initialBalance); } Code: 4.8 C# Note: Once the above code is changed in Account Form, btnSet_Click is no more useful and thus it can be removed.

15

Deccansoft Software Services

OOPs Chapter-4

Destructor
A destructor is used to release the resources that an object is holding. When an object is ready to be destroyed Finalize method / Destructor is called on that object. In C++, destructor of a class is responsible for destroying all the other objects which the object of this class has created during its lifetime. (In C++ we dont have Garbage collector) In .NET, all the dependent objects are automatically ready for Garbage Collection when the main object doesnt have any references thus the destructor here doesnt have same significance as in C++. Syntax in C#: Syntax in C#: ~<class name>() { }. Note: A destructor in C# cannot have any access modifiers

Because its not predictable when the Destructor method will be executed, it is not recommended to only rely on destructor for releasing of resources and thus Microsoft has suggested two methods that can be invoked by the programmer for the release of resources i.e. Close() or Dispose().

16

Deccansoft Software Services

OOPs Chapter-4

Working with static Members


For every new instance of a class all the instance members are allocated memory, but static field members of a class are allocated memory only once irrespective of the number of objects created and they are allocated memory when the class is loaded. These members are also called class members and are accessed outside the class using class name. Note: 1. A class is loaded when either the static members of the class is accessed for the first time or when the first instance of the class is created. A class once loaded will remain in memory permanently and thus also are all static members of that class. 2. A public static member of a class can be used as Global member of the application because it can be assessed using class name from any part of the application. Static Constructor: A constructor is defined with the keyword as static (in C#). It is used to initialize the static member dynamically and is executed when the class is loaded. This is invoked by the CLR when the class is loaded by it and hence cannot be overloaded nor can be declared with any accesses specifier like public or private. Series of events that occur when the first object is created: 1. 2. 3. 4. 5. Class is loaded. Static members are loaded and allocated memory. Static constructor is executed. Instance members are loaded and allocated memory. Instance constructor is executed. Note: Static Constructor cannot access Instance members of the class. This is because when the static constructor is executed the instance members are not allocated any memory. Perform the following steps sequentially 14. Create a new static variable in Account class: public static int MinBalance = 500; //Add this in Account class 15. In Withdraw method replace the constant value 500 with the static member "MinBalance": if (this.Balance - amount < MinBalance) //replace 500 with MinBalance 16. In Form: Add btnGetMB and btnSetMB buttons and txtMB textbox with the following code: private void btnGetMB_Click(object sender, EventArgs e) { txtMB.Text = Account.MinBalance.ToString();

17

Deccansoft Software Services

OOPs Chapter-4

} private void btnSetMB_Click(object sender, EventArgs e) { Account.MinBalance = int.Parse(txtMB.Text); } 17. Create a new static variable in Account class: public static int _PrevId; 18. Make the following changes in default constructor of Account class to autogenerate the next ID instead of user entering a value: public Account() { _PrevId += 1; _Id = _PrevId; } 19. Id now should be changed to a ReadOnly property as we are autogenerating the new IDs. For this we can remove the setter as shown below: public int Id { get { return _Id; } //set //{ // if (idAlreadySet) // throw new ApplicationException("Id is already set"); // _Id = value; // idAlreadySet = true; //} } 20. Because Id is now auto increment field generate by default constructor, remove the id parameter from parameterized constructor of Account Class: Public Sub New(ByVal name As String, ByVal balance As Decimal) Me.Name = name Me._Balance = balance End Sub Public Sub New(ByVal a As Account) Me.New(a.Name, a.Balance) End Sub 20. Remove id argument while creating the Account object in btnCreate_Click of AccountForm: Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click 'Dim id As Integer = Integer.Parse(txtId.Text) Dim name As String = txtName.Text Dim initialBalance As Decimal = Decimal.Parse(txtBalance.Text) Dim a As New Account(name, initialBalance) 'Removed id arguments End Sub 21. Remove a.id argument for updating the Account object in btnSet_Click of AccountForm:

18

Deccansoft Software Services


private void btnSet_Click(object sender, EventArgs e) { //a.Id = int.Parse(txtId.Text); a.Name = txtName.Text; a.Deposit(decimal.Parse(txtBalance.Text)); } Code: 4.9 VB

OOPs Chapter-4

Perform the following steps sequentially 14. Create a new Shared variable in Account class: Public Shared MinBalance As Integer = 500 'Add this in Account class 15. In Withdraw method replace the constant value 500 with the static member "MinBalance": If Me.Balance - amount < MinBalance Then 'replace 500 with MinBalance 16. In Form: Add btnGetMB and btnSetMB buttons and txtMB textbox with the following code: Private Sub btnGetMB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetMB.Click txtMB.Text = Account.MinBalance.ToString() End Sub Private Sub btnSetMB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetMB.Click Account.MinBalance = Integer.Parse(txtMB.Text) End Sub 17. Create a new static variable in Account class: Public Shared _PrevId As Integer 18. Make the following changes in default constructor of Account class to autogenerate the next ID instead of user entering a value: Public Sub New() _PrevId += 1 _Id = _PrevId End Sub 19. Id now should be changed to a ReadOnly property as we are autogenerating the new IDs. For this we can remove the setter as shown below: Public ReadOnly Property Id As Integer 'Add ReadOnly keyword to Property definition Get Return _Id End Get 'Set(ByVal value As Integer) ' If (idAlreadySet) Then ' Throw New ApplicationException("Id is already set") ' End If ' _Id = value ' idAlreadySet = True 'End Set End Property 20. Because Id is now auto increment field generate by default constructor, remove the id parameter from parameterized constructor of Account Class: Public Sub New(ByVal name As String, ByVal balance As Decimal) Me.Name = name Me._Balance = balance End Sub Public Sub New(ByVal a As Account) Me.New(a.Name, a.Balance)

19

Deccansoft Software Services

OOPs Chapter-4

End Sub 20. Remove id argument while creating the Account object in btnCreate_Click of AccountForm: Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click 'Dim id As Integer = Integer.Parse(txtId.Text) Dim name As String = txtName.Text Dim initialBalance As Decimal = Decimal.Parse(txtBalance.Text) Dim a As New Account(name, initialBalance) 'Removed id arguments End Sub 21. Remove a.id argument for updating the Account object in btnSet_Click of AccountForm: Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSet.Click 'a.Id = Integer.Parse(txtId.Text) a.Name = txtName.Text a.Deposit(Decimal.Parse(txtBalance.Text)) End Sub Code: 4.9 C# Screenshots of sequential execution of the program: 1. Run the program

2. Enter name and balance and click on Create

20

Deccansoft Software Services


3. Click on Clear

OOPs Chapter-4

4. Click on Get

5. Change the Name and click on Set

6. Click on Clear again

21

Deccansoft Software Services

OOPs Chapter-4

7. Click on Get to check whether the changes were saved.

8. Enter Deposit amount and click on Deposit.

9. Click on Get to see the updated balance.

22

Deccansoft Software Services

OOPs Chapter-4

10. Enter MB(Minimum Balance) (1000 as shown below) and click on Set MB button.

11. Try to withdraw amount that will leave the account with less than minimum balance.

12. Error is displayed. You can click on Continue but the recent withdrawal will not be saved.

23

Deccansoft Software Services

OOPs Chapter-4

Static Methods: A method which does not have anything to do with the state of the object can be marked as static method. Eg: class File { public static void Copy(string srcPath,string destPath) { . . . } } Note: All methods and properties (procedures) of the class irrespective of whether they are static or not are allocated memory only once. 1. Outside the class a static members of a class can be accessed using class name where as the instance member of a class must be accessed using a reference variable referring to an object of that class. 2. Instance members of the class cannot be accessed in a static constructor or any other static method or property of the class (unless it is qualified by a reference variable referring to an object of that class). For Example public static void Foo() { //_Balance = 100; // Is Invalid Accout a = new Account(); a._Balance = 100; // IsValid because _Balance is qualified by a which is reference to an object. } 3. An instance member can access static members of the class. 4. this cannot be used in the static member of a class. 5. A class in C# can be declared as static and such a class can have only static members and instance members are not allowed. Also such a class cannot be instantiated. static class Demo {

24

Deccansoft Software Services


} public static int P1; public static void Foo() { }

OOPs Chapter-4

Summary:
In this section, we have seen the tenets of object oriented programming and how one can use these in one of the real life requirements.

25

You might also like