0% found this document useful (0 votes)
15 views83 pages

Understanding Object Oriented Programming Concepts

Uploaded by

Niranjan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views83 pages

Understanding Object Oriented Programming Concepts

Uploaded by

Niranjan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Object Oriented Programming

Objectives
 A trip to object oriented programming concepts
 Define an object
 Identify an object state and behavior
 Define a class
 Know about Data Abstraction
 Know about Data Encapsulation
 Know about Polymorphism
 Know about Inheritance
 Object based versus oriented

Introduction

We would like to look at the difference between an object and class. We will identify
an object attributes and functionalities. We will understand data abstraction and
encapsulation with real time examples. We will explore the multiple forms of an object
through polymorphism. We will look to implement reusable and extensible
components. We ensure that data is much secured to provide authentic access.
We basically understand oops concept in a real world approach.

Once you get to object Ville, you might never come back.

What is an object Oriented Programming?

It is a design philosophy or mechanisms that binds the attributes of an object


as state, and functionalities of an object as behavior and access them through a pool
of objects.
“Smalltalk was the first object oriented programming language.”
C++, C#.NET, [Link], Java are some other object oriented programming languages.
Any programming language that can implement oops concept is termed by object oriented.

OOPS Concepts

 Object

 Class

 Data Abstraction

 Data Encapsulation

 Polymorphism
 Inheritance
Object

Consider a few real time objects irrespective of being living or


nonliving that surround us. Few to list pen, apple, parrot, table, dairy milk, tiger,
flag, student, paper and so on to list on cards.

If anyone would ask me “what is an Object?” – I would simply reply him a pen is
an object also, girl is an object. Here pen is a non-living object and girl a living object.

Object Attributes

Let’s gather Attributes or characteristics associated with pen object – color,


height, brand, name, weight, brand, etc. similarly, a girl object– name, height, weight,
color, eyes, etc. These are actually attributes that been associated with a particular
object. This is what referred by the state of an object.

Object Functionality

Pen functionality includes to draw, scratch, shade, scribble and so on.


Girl functionality includes read, write, play, dance, sing, love, sleep and so on.
This is what referred by the behavior of an object.

State refers to what an object knows (living object) or owns (non-living object) by itself.
A living object has a brain to know its attributes, whereas, a non-living owns them.
Behavior refers to what an object can do or does or functionality associated with them.

Object is a real world element which has State and Behavior irrespective of living or
non-living. State refers to what an object knows or owns by itself, whereas behavior
refers to what an object can do or does or simply the functionality of an object.
It can also treat as a runtime instance or entity of a class declared.

Class

When I talk about an object (say Dog), I always refer to a class (say Animal).
When I talk about an object (say Parrot), I always refer to a class (say Bird).
When I talk about an object (say Prati), I always refer to a class (say Girl).

What do the above statements imply?

Unless an Animal exists, a Dog can’t exist.


Unless a Bird exists, a Parrot can’t exist.
Unless a Girl exists, Prati can’t exist

hence, a class becomes mandatory to declare an object.

Class is a mandatory template or skeleton that required to declare an object.


It can also be treated as an ADT (Abstract Data Type) which binds Data members that
specify the State and Member functions that specify the Behavior of objects declared
for it. Always an object is of type any class.
A class is also treated as collection of objects.
How to design a class?
When you design a class, think about the objects that will be created from that class type.
Think about:
Things the objects knows (also referred by instance variables, that represent state)
Things the object does (also referred by methods, that represent behavior)

Difference between class and object

An object is instance or specimen of class, whereas class is blue print that defines the
variables and methods common to all objects of a particular class. Example: (Software
design for Bird Pet Management System)
Class Bird
Common Attributes: Color, Height and Name
Common Behaviors: Fly, Eat, Sleep
Objects of type Bird
States: (Green, 19.23cm, Parrot) (Yellow, Sparrow, 23.19) etc.
Behaviors common: Fly, Eat and Sleep

Data Abstraction

Abstracting relevant attributes from an object, while ignoring irrelevant attributes of an


object is referred by Data Abstraction.

Its, too technical definition, let’s understand in real world with following example.

Let’s consider four persons standing in an army school bus stand. First person is a
marketing manager, second a car mechanic, third a cute girl (say prati), and finally a
good boy (say sandy). All are observing an object (say Blue Ritz Car).

As a marketing manager I would like to abstract the attributes or functionality


related to marketing strategies, may be mileage, capacity, model, style etc., and
ignore other attributes related to machinery.

As a car mechanic, I am least bothered about marketing strategies; rather I would


take much interest towards the machinery attributes like motor, engine, battery, etc.

Finally, boy and girl just would dream to have a long drive over the highway roads.
They are least bothered about marketing or machinery attributes or functionality.

In the above example, if we observe, all the persons are in definite abstract of some
attributes or functionality based on their domain and also ignore attributes or
functionality.
Data Encapsulation

Binding the state and behavior into a capsule called class and access them through
a pool of objects is referred by Data Encapsulation. It represents data hiding.

How data is encapsulated in a class? : By using Private, Public, Protected

Let’s understand with following example: (Television Object)

It’s a known fact that an object being living or non-living private attributes is not
exposed whereas public attributes are only exposed to the world.

If we talk about a Television, it has an inbuilt electronic circuit, nicely


covered with Cabin, fixed button ports and a remote control to access (for lazy
operators).

Assume television made completely public: open electronic circuit, cabin open, open
switches, remote control exposed, then the object is in risk.

Also television made completely private: closed electronic circuit, closed cabin,
but don’t provide fixed switches or remote control to operate, that makes object
dummy.

Hence, we should never declare an object completely public or private in nature.

I mean private members should not be exposed whereas public members need to be
exposed.

For instance, if I need to increase the volume level, no need to keep my hand
directly into private electronic circuit; instead I should use the remote control
public option VOL+ to increase volume. There is a discipline need to be followed.

“Always declare object state as private and define object behavior as public”

Polymorphism

Polymorphism refers to “multiple forms of an object with common functionality”.


Let’s understand with following two real time examples:

Example 1: (ALL ROUNDER)

People do say that I am an all rounder – say Faculty and Singer. Hence my functionality
involves teaching and singing.

In current example, my form is changing from object Faculty to object Singer.


Also my functionality is changing from teaching to Singing. Here we observe
different form and different functionality. Hence, it can’t be polymorphism.
Polymorphism entertains only change in form but not the change in functionality.

What could be the best analogy?

Example 2: (Teacher)

I can teach C language also C++ language. Here, object form is changing from C
faculty to C++ faculty, but both objects functionality teaching remains common.

Similarly, I can speak Hindi language also English language. Here, object form is
changing from Hindi spoken to English spoken, but both objects functionality
speaking remains common.

Inheritance

Inheritance refers to heredity that involves reusability and extensibility.

Let’s understand with following real time examples:

Example 1: (basic calculator and scientific calculator)


Consider Basic and scientific calculator. The former don’t have the scientific functions as
in later. later model will definitely includes the basic functionalities like plus, minus, etc
from former model that is referred by reusability, and also new features been added is
extensibility.

Example 2: (Hero Honda versus Splendor Plus)


Consider Hero Honda splendor and splendor plus motor bikes. The Former don’t have
the self start utility as in later. Later model will definitely include the best
components from former model that is referred by reusability, and also new features
been added like self start is referred by extensibility.

Example 3: (Windows 98 versus Windows 7)


Consider windows 98 and windows 7 operating system. Former features are
reusable components in later operating system and also added some
extensible features.

How to generalize inheritance in English?

In general English wherever IS-A relationship exists it implies inheritance.


Prati is a girl.
Sandy is a boy.
Parrot is a bird.

In all the above statements right side entity is Parent class and left entity is Child class.
Why it’s not vice versa? : Every Parrot is a bird, but every bird can’t be parrot.
In contrast to IS-A relationship there exists HAS-A relationship between Class and its
sate. For Example: Room Class has a chair, has a table, has a blackboard, etc.
IS-A relationship Child Class and Parent Class
HAS-A relationship Class and its State only

Object Based Programming Concepts


OOPS Concepts – Inheritance = Object Based Programming
Concepts Example: Visual Basic 6.0 language

let’s understand with an example: Consider 2 programmers by name John an object


based programmer and Bob object oriented programmer. Task is given to create a
scientific calculator given a base calculator code with base functions Plus, Minus etc.

Bob will reuse the existing functions and extend new functions like Log, Exp etc.
John need to recode entire existing and new functions due to lack of Inheritance.

Summary
We understood entire oops concepts in a real world approach. We identified the
state and behavior of objects belongs to certain class. We explored completely about
the data abstraction, data encapsulation, polymorphism and inheritance. We
differentiated an object based and oriented programming approach.
Objectives

 Introduction to class and object


 Class Members
 Object Memory Allocation
 Differentiate class and structure
 Access Specifier’s
 Properties Read and Write
 Automatic Properties
 Inline Functions
 Const Member Functions
 Nesting Member Functions

Introduction to Class and Object


Object is a real world element which has state and behavior. A class refers to a
mandatory template or skeleton to declare an object.

Class Syntax: to declare Name, Members = Data Members + Member Functions

class <class-name>
{
/ Class Data Members represent state

/ Class Member Functions represent behavior


};

Class members can be classified under following categories:


- Based on state and behavior
- Based on access specifier
- Based on static and non-static (discussed later in static concept)

Class Members based on State and Behavior

Class members that represent state are referred by Data Members.


Class members that represent behavior are referred by Member Functions or Methods.

Data members are actually the local variables that represent the attributes
associated with the objects declared for a particular class.
Example: int id; variable id will represent student ID attribute

Member functions are actually the user defined functions that represent
functionality or behavior associated with the objects declared for a particular
class.
Example: void AcceptID(); function AcceptID represent student behavior to add ID
Class Members based on Access Specifier’s

C#.NET supports three types of access specifier’s : Private, Public and Protected
Default access specifier in C++ is Private (can’t be accessed even with object of same class).

Private Class Members: members can be accessed only within the class.
Public Class Members: members can be accessed within or outside the class.
Protected Class Members: members can be accessed within derived class.

Note: OOPS Principle “state is declared private and behavior defined public”

How to declare an Object of a particular class?


Syntax: ClassName <objectname>;
Example: Student s1;

How to use a class?


Simply declare an object of the particular class and call compatible members.

Dot Operator
It is used to access the compatible member of the class along the object ([Link]).

What is Scope Resolution Operator (:: ) ? (Only for C++ Programmers)

In C++ Class member functions can be declared within or immediate of class. If we


declare immediate to the class then we need to place a membership label inside the
function definition.

Membership Label = Class Name:: Scope Resolution Operator

Why to declare membership label?

Consider two classes Customer and Product with a common behavior AcceptID that
manages to accept new Customer and Product ID, written in one C++ Program.
If I don’t use the membership label, it leads to ambiguity error when I call AcceptID
function.
It help us to identify the function does it belong to.

Note: C#.NET doesn’t support Scope Resolution operator as like C++

Object Memory Allocation

When the first object of the class is created the memory is allocated to all the data
members as well member functions as a single unit and placed in the heap memory.
When the second object of the class is created the memory is allocated again to all
the data members only and not to the member functions and placed in the heap
memory.

Ultimately, Irrespective of any number of objects created every time the memory will
be allocated to all data members, whereas memory allocated only once to the
member functions.

(Why?) : As the state of an object can alter, but not the functionality.

Difference between Structure and Class


- Structure is value type whereas a class is reference type.
- Structure holds only state majorly whereas a class holds state and
behavior.
- Structure can’t be inherited whereas a class can be inherited.

Value Type Reference Type Heap Memory


VAR = VALUE VAR VALUE
int n = 19;
Student s1; [Link] = 19
Real world Example: Television Remote control is a reference variable to television object.

Obj01 - Program on Class - Declare, Define, Call State and Behavior

Part A: Add class ANIMAL explicit into solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj01
{
class Animal
{
/ Data Members - Represent State of

objects private string name;

/ Member Functions - Represesnt Behavior of objects

public void AcceptName()


{
[Link]("\n May I Know Your name? \t");
name = [Link]();
}

public void DisplayName()


{
[Link]("\n My name is \t" + name);
}
}
}

Part B – PROGRAM Class – Call Explicit declared class ANIMAL

using System;
using [Link];
using [Link];
using [Link];

namespace Obj01
{
class Program
{
static void Main(string[] args)
{
/ Reference varible (yet to be

referred) Animal a;

/ Object is created of type Animal

a = new Animal();

// Access the behaviors

[Link]();
[Link]();

}
}
}
(OR)

Part A + B – PROGRAM Class with implicit declaration of class ANIMAL

using System;
using [Link];
using [Link];
using [Link];

namespace Obj01
{

class Animal
{
/ Data Members - Represent State of

objects private string name;


// Member Functions - Represesnt Behavior of objects

public void AcceptName()


{
[Link]("\n May I Know Your name? \t");
name = [Link]();
}

public void DisplayName()


{
[Link]("\n My name is \t" + name);
}
}

class Program
{
static void Main(string[] args)
{
/ Reference varible (yet to be

referred) Animal a;

/ Object is created of type Animal

a = new Animal();

/ Access the

behaviors

[Link]();

[Link]();

}
}
}
Obj02 - Program on Class - Access Specifiers Private, Public

Part A – Add CAT class explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj02
{
class Cat
{
/ Data Members - Represent State of

objects

private string name;

/ Member Functions - Represesnt Behavior of objects

public void AcceptName()


{
[Link]("\n May I Know Your Name? \t");
name = [Link]();
}

public void DisplayName()


{
[Link]("\n My name is \t" + name);
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj02
{
class Program
{
static void Main(string[] args)
{
// Object

Cat c = new Cat();

[Link](); // Can Access

[Link] = “Pummy”; // Can’t Access

}
}
}

Obj03 - Program on Class - Alternatives to set Static and

Dynamic State Part A – Add Student Class Explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj03
{
class Student
{
// State

private int id;


private string _name;
private int age;

// Behavior

public void SetID(int val)


{
/ Static Definition -
Method 1 id = val;
}

public void SetName(string name)


{
/ Static Definition -
Method 2 _name = name;
}

public void SetAge(int age)


{
[Link] = age;
}

public void AcceptName()


{
// Dynamic Definition

[Link]("\n May I Know Your Name?");


_name = [Link]();
}

public void DisplayID()


{
[Link]("\n HI... My ID is " + id);
}

public void DisplayName()


{
[Link]("\n HI... My Name is " + _name);
}

public void DisplayAge()


{
[Link]("\n HI... My Age is " + age);
}
}
}
Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj03
{
class Program
{
static void Main(string[] args)
{
/ Reference varible (yet to be

referred) Student s;

/ Object is created of type Animal

s = new Student();

/ Access the behaviors

/ Static Definition

[Link](19);

[Link](“Parrot”);
/ [Link](19);

[Link]();

[Link]();

[Link]();

/ Dynamic

Definition

[Link]();

[Link]();

}
}
}
C#.NET Properties versus Methods

Property always represent the state of an object. Memory is allocated temperory at


runtime.
Methods always change the state of an object. Memory is allocated permenant at runtime.

C#.NET supports only two types of properties – READ property using GET keyword
and WRITE property using SET keyword.

C#.NET also introduced recently Automatic Properties that shortens the code length.
Example: Television VOLUME property represents current volume level, where
as , VOL+ method changes the volume state by increasing its value.

Difference between Properties and Methods

1. Properties represent state, whereas methods alter state.


2. Properties never take any arguments, whereas methods may or may not.
3. Properties do not reside on stack as like methods.
4. Properties can be made read or write only, methods not possible.

Obj04 - Program on Class - Read and Write Properties

Part A – Add BOOK class explicitly into solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj04
{
class Book

{
private int id;

private string name;

// Properties

public int BookID


{
// Read Property

get
{
return id;
}

// Write Property

set
{
id = value;
}
}
public string BookName
{
// Read Property

get
{
return name;
}

// Write Property

set
{
name = value;
}
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];

using [Link];

namespace Obj04
{
class Program
{
// Obj02 - Class with Read and Write Properties

static void Main(string[] args)


{
Book b = new Book();

[Link] = 1923;

[Link] = "Dove Wonders";

// Accessing Properties

[Link]("\n Book ID is " + [Link]);


[Link]("\n Book Name is " + [Link]);
}
}
}

Obj05 - Program on Class – To Understand Properties and Methods

Part A – Add Class REMOTECONTROL into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj05
{
class RemoteControl
{
// State

private int _volume;

// Behavior - Constructor - Initialize Objects

public RemoteControl()
{
// Default Constructor

[Link]("\n Default Constructor");

public RemoteControl(int value)


{
/ Parameterized Constructor

_volume = value;

[Link]("\n Default Constructor");


}

// Behavior - Property - Represent Current State of Object

public int Volume


{
get
{
return _volume;
}

set
{
_volume = value;
}
}

/ Behavior - Methods - Change The State of Object public void


VolumePlus()
{
_volume++;
}

public void VolumeMinus()


{
_volume--;
}

// Behavior - Destructor - Deallocates Objects

~RemoteControl()
{
[Link]("\n Object Commit Suicide");
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];

using [Link];
namespace Obj05
{
class Program
{
static void Main(string[] args)
{
RemoteControl rc = new RemoteControl();
[Link]("\n Input Volume Level "); [Link] =
[Link]([Link]());

[Link]("\n Current Volume Level \t " + [Link]);

[Link]();

[Link]("\n Current Volume Level \t " + [Link]);

[Link]();

[Link]("\n Current Volume Level \t " + [Link]);


}
}
}

Obj06 - Program on Class – Automatic Properties

Part A – Add BOOK class explicitly into solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj06
{
class Book
{
private int id;

private string name;

// Properties

public int BookID


{
// Read Property

get;
/ Write
Property set;
}
public string BookName
{
/ Read
Property get;
/ Write
Property set;

}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj06
{
class Program
{
// Obj02 - Class with Read and Write Properties

static void Main(string[] args)


{
Book b = new Book();

[Link] = 1923;

[Link] = "Dove Wonders";

// Accessing Properties

[Link]("\n Book ID is " + [Link]);

[Link]("\n Book Name is " + [Link]);


}
}
}

Inline Functions and Inline Keyword

In C++, Class member functions can be defined within or outside the class. If the
functions are defined within the class then they are referred as Inline functions. Also
to make non-inline functions to behave as inline function we need to prefix the
function prototype with inline keyword.
What is the advantage of Inline functions over non-inline functions?

Advantage of the function being Inline function is that it need not be compiled
every time a program when forwarded to compile. It only once compiles and stays
for future usage.

Example:
Let’s consider you are developing an application for a College. You may define
many of the behaviors like Register, AddStudent, UpdateStudent, Topper, etc. out
of which we may use few behaviors very frequently. Those functions which are
needed to be called frequently are made Inline. They behave like Cache storage in
memory.

Also, if u decides later a non-inline function to be converted to inline function, we


need to use the keyword inline.

 C#.NET doesn’t support INLINE keyword as like C++.


 Every method defined in a class in C#.NET is by default inline in nature.

Nesting of Member Function

Class member functions can be nested, implies, one member function can give
implicit call to other member function. This mechanism improves readability of the
source code.

Obj07 – Program on Nesting of Member Functions

Part A – Add ITEM class explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj07
{
class Item
{
private int id;

private string name;

public void AcceptID()


{

[Link]("\n May I Know Your ID? \t");


id = [Link]([Link]());
}
public void DisplayID()
{
[Link]("\n My ID is \t" + [Link]());
}

public void AcceptName()


{
[Link]("\n May I Know Your Name? \t");
name = [Link]();
}

public void DisplayName()


{
[Link]("\n My Name is \t" + name);
}

// Nesting of Member Function

public void AcceptDetails()


{
AcceptID();
AcceptName();
}

public void DisplayDetails()


{
DisplayID();
DisplayName();
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj07
{
class Program
{
// Obj06 - Program on Nesting of Member Functions
static void Main(string[] args)
{
Item item1 = new Item();

// Call Nesting Member Functions

[Link]();
[Link]();
}
}
}

Const Member Function

In C++, Class member functions can also placed as const member functions. Member
functions that do not alter the state of the objects need to be made as const type.
If you try to make the functions which alter the state as const it will lead to Errors
(in static definition type) and lead to warnings (in dynamic definition type). It also
improves readability of the source code.

C#.NET doesn’t support const member functions as like C++.

C#.NET - Array Members inside a Class


A class can include a member of Array type.

C#.NET - Array of Objects


A class can have numerous objects which can be declared individually or replaced as an
array.

Obj08 – Program on Array of Objects

Part A – Add ANIMAL class explicitly into Solution


using System;
using [Link];
using [Link];
using [Link];

namespace Obj08
{
class Animal
{
/ Data Members - Represent State of

objects private string name;

/ Member Functions - Represesnt Behavior of objects


public void AcceptName()
{

[Link]("\n May I Know Your Name? \t");


name = [Link]();
}

public void DisplayName()


{
[Link]("\n My Name is \t" + name);
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj08
{
class Program
{
static void Main(string[] args)
{
// Declare an Array of Objects - Reference Variables

Animal[] MyPets;
MyPets = new Animal[3];

/ Make the 3 reference variables to 3

objects MyPets[0] = new Animal();

MyPets[1] = new

Animal();

MyPets[2] = new

Animal();
for (int i = 0; i < [Link]; i++)
{
MyPets[i].AcceptName();
}

// Display Names

for (int i = 0; i < [Link]; i++)


{
MyPets[i].DisplayName();

}
}
}
}
Objectives
 Memory Allocations
 Static local variable
 Static Data Member
 Static member Functions
 Object as an argument
 Object as return type
 Why the MAIN function need to be declared as static?

Memory Allocations

Irrespective of any programming language C, C++, Java, C#.NET etc. translators


allocate the variables and functions inside memory by means of STACK Memory, HEAP
Memory and GLOBAL Memory.

STACK memory will be called to allocate memory for all the user defined functions.
Whenever a function is called, immediately a STACK will be created by the function
name. By PUSH operation it allocate memory to all the function parameters, local
variables (if exists) inside function and carry on operations. While terminations of
function POP operation will clear the STACK.

Example: void Add(int s, int p)


Z=S+P Pop Z = S+P
{
int z; Push Z Pop Z
z = s + p; Push P Pop P
}
Push S Pop S
Add(19,23); ADD ADD
Function Function Terminate
Call

Global Memory
Global memory will be called in the case of Global variables and Static variables.

Heap Memory
Heap memory will be called in the case of address based pointers and referenced based
objects.

It represents the dynamic memory allocation.


Static Local Variable
Static local variables also referred by storage class, are the variables that retains its
value even after the function been called. Static local variables are allocated memory
only once.
Example:
void fun()
{
static int n = 19;
cout<<" Value of N \t " <<n;
n = n + 1;
}
void main()
{
fun(); //Prints 19;
fun(); //Prints 19;
fun(); // Prints 19;
}

Static Class Data Members and Member Functions


consider a class Student with attributes – ID, Name and functionalities – AcceptID,
DisplayID.
Assume three objects have been created for the class Student.

id = 19 id = 14 id = 23
name = prati name = sp name = sandy

S1 S2 S3

Few points to note:


- S1, S2, S3 objects are holding independent specific state.
- Alter in the state of any object will not affect other object.
- I mean [Link] is specific to S1 object and [Link] is specific to S2 object.
- Hence the states of the objects S1, S2, S3 are not sharable.

When to declare data member as static?

When we need to share a resource among the objects then declare it as static.

For example: Student attributes like ID, Name can’t be declared as static because it is
specific to a student. In contrast, attributes like topper, average height, average
weight, strength of the class need to be declared as static as they are generic to any
student of class.

Similarly behaviors like AcceptID, AcceptName are specific in nature. In contrast


GetAvgHeight, GetAvgWeight, ClassTopper, ClassStrength behaviors are generic in
nature.

Always declare specific members as non-static and generic members as static.

General features of static members:


- Static members though declared along the class, they won’t share
memory in the HEAP as like instance members.
- As they are not sharing memory inside the heap, they can’t be accessed through
object.
- Memory is allocated only once and resides in Global memory to get access.
- Static members can have access only to other static members.
- Static members can’t access instance members.
(Why? As they don’t share memory in Heap memory)
- Instance members can access static members.
(Why? As static members reside in Global memory)
- Static member’s state is generic in nature, hence altering the state affect all object.
- Static member’s are accessed with class name and scope resolution operator.

Static int count = 0;

S1 S2 S3
id = 19 id = 14 id = 23
name = prati name = name =
love sandy
Obj09 – Program on Static Data Members and Member Functions

Part A – Add STUDENT class implicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj09
{
class Student
{
private int id; // Specific Non-Static Attribute

static int count; // Generic Static Count Attribute

public void AcceptID()


{
[Link]("\n May I Know Your ID? \t");
id = [Link]([Link]());

/ Increment Count Variable


count++;
}

public void DisplayID()


{
[Link]("\n My ID is \t " + [Link]());
}

// Static Method
public static void Strength()
{
[Link]("\n Total Students \t " +
[Link]());
}
}
}
Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj09
{
class Program
{
// Obj09 - Program on Static Members

static void Main(string[] args)


{
Student s1, s2, s3;

s1 = new Student();
s2 = new Student();
s3 = new Student();

[Link](); // Count = 0

[Link]();
[Link]();
[Link]();

[Link](); // Count = 3

[Link]();
[Link]();
[Link]();
[Link]();

[Link](); // Count = 7

}
}
}

Why MAIN Function need to be declared as STATIC?


CLR at the time of class loading need to access the MAIN method even before the first
object of the class had been created.

What is a static class?


A class in which every member is static in nature i.e. every data member and member
function.
Example: predefined class CONSOLE. For a static class no need to declare an object to
access.

Friend Functions
As I talk about private members of the class can’t be given access even through
the object declared for the same class. But friend function is the medium that
makes it possible. It is Not entertained in the high end [Link] and Java languages
anymore. It is inbuilt with the read only property. Also two classes can be made
friends by defining the common friend function in both classes.

Example 1: Let’s assume two classes Principal and Staff. Both need to pay tax to the Govt.
So we can define a common friend function PayTax in both classes.

Example 2: TV object has internal circuit is private which is not accessible. But a
mechanic (friend) can access it as he knows how to repair it.

Features of friend functions:


- Friend function though declared along the class, they won’t share memory in Heap.
- As they won’t share memory inside the heap, they can’t be accessed through
object.
- Friend function needs to be parameterized with class object.
- Friend function is accessed directly as like user defined function.

What is difference between user-defined and friend function?


User defined function may not have arguments, whereas friend function needs to
have class object as an argument.

C#.NET doesn’t support FRIEND function concept as like C++.

Object as Argument and Return Type

Member function can have Arguments of type variables, constants, pointers,


addresses, arrays, functions, structures. It can also have objects as arguments and
return types.
Also, a member function of return type object should be only class type.

Example: Student S1, S2; be the two objects of type Student class
Assume S1 object hold a state of id=19 and S2 with id = 23
S1=S2; (what is object assignment?)

Heap Memory (Student Object) Heap Memory (Student


[Link] = 19 [Link] = 23 Object)
[Link] = 19 [Link] = 23

S1 S2
S1 S2
After Assignment – S1 object gets unreferenced and referred to object S2.
Hence, both S1 object and S2 object refer to same state of S2 object.

Example: Assume Sandy object is referred to fan and Prati object is referred to
parrot. Prati invite sandy to look the parrot, then Sandy object will un-
reference the fan state and refer to the parrot state of the Prati object.

Remember: An object can refer to any number of references, whereas, a


reference can refer to only one object at a time.

Note: Static methods can access non-static data by class reference as an

argument. Obj10 – Program on Objects as Function Arguments Part A – Add

NUMBER class explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj10
{
class Number
{
private int value;

public void AcceptValue()


{
[Link]("\n Input Value ");
value = [Link]([Link]());
}

public void DisplayValue()


{
[Link]("\n Number Value is \t" +
[Link]());
}

// Function Add with two object Arguments

public static void Add(Number n1, Number n2)


{
Number n3 = new Number();

[Link] = [Link] + [Link];


[Link](" Sum is " + [Link]());
}
}
}

Part B – Program Class

using System;
using [Link];

using [Link];
using [Link];

namespace Obj10
{
class Program
{
// Obj10 - Program on Objects as Arguments

static void Main(string[] args)


{
Number s = new Number();

Number p = new Number();

/ Accept First Number

[Link]();

/ Accept Second Number

[Link]();

/ Call Add Static Function with 2 object arguments

/ [Link](s, p);
}
}
}

Obj11 – Program on Objects as Function Return Types

Part A – Add NUMBER class explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj11
{
class Number
{
private int value;

public void AcceptValue()


{
[Link]("\n Input Value "); value =
[Link]([Link]());
}

public void DisplayValue()


{
[Link]("\n Number Value is \t" +
[Link]());
}

// Function Add with two object Arguments and class return type

public static Number Add(Number n1, Number n2)


{
Number n3 = new Number();

[Link] = [Link] + [Link];

return n3;
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj11
{
class Program
{
// Obj11 - Program on Object as Function Return Type
static void Main(string[] args)
{
Number s = new Number();
Number p = new Number();

[Link]();
[Link]();

/ Function Result stored as an object Number sp

= [Link](s,p); [Link]();
}
}
}

Objectives
 Default Constructors
 Parameterized Constructors
 Copy Constructors
 Private Constructors
 Static Constructors
 Object Life Cycle Sequence
 Destructors

Constructors
In C++, Consider a class Student with attributes ID, Name.
class Student
{
private:
int id = 19; // Leads to error
};
It won’t lead to error in C#.NET as it takes as default state.
In the above example, you are trying to provide the state while declaring it. It’s invalid.
(Why? You are trying to give the name for a baby without giving birth).

Constructor is a special member function that initializes the state of an object.


(Why it’s special member function? As it resembles the class name)

General Features of constructors:

- Special member function as it resembles class name


- Need be declared public (if made private, we can’t create object) in nature
- It can’t return any value
- It can be parameterized
- Invokes automatic when the object is created, rather than been called by object
- Constructors cannot be inherited

Why constructors can’t return any value?

[Link] as the name implies used for construction or initialize the state,
it would be mutually exclusive situation to expect the state, when you are try
to set the state. I mean you are trying to retrieve the student ID without that
wait’s for your value.

2. At the max what it can return – state details or object details. State details
can’t return as you have not provided. Object details can’t return as the object
yet to be created.

Types of constructors: Default, Parameterized and Copy Constructor

Default : invokes automatic when object is created and set the state to default values.
Parameterized: invokes and set the states by the values passed while object declaration.
Copy : invokes and set the common state for objects been copied.
Assume S1 = S2, the object S1 gets unreferenced and set to share S2 state.

Example: Banking Software supports a customer to create savings as well salary


account. Salary account opens with zero balance, whereas savings account with
minimum balance. Here, we can use DEFAULT constructor for salary and
PARAMETERIZED constructor for savings bank account.

Obj12 - Program on Default, Parameterized and Copy Constructor

Part A – Add Class BIRD explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj12
{
class Bird
{
private string name;

public Bird()
{
[Link]("\n Default Constructor : Object born");
}

public Bird(string val)


{
name = val;

[Link]("\n Parameterized Constructor:


Object born");
}

public void DisplayName()


{
[Link]("\n My Name is \t " + name);
}

}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj12
{
class Program

{
static void Main(string[] args)
{
Bird bird1, bird2, bird3,bird4;

bird1 = new Bird();

/ bird2 = new Bird("Parrot");

bird3 = new Bird("Peacock");


/ Copy Constructor refers to same state

/ bird4 = bird3;

/ [Link]();

/ [Link]();

}
}
}

Destructors
“Just funny you are trying to shoot a person, who is ready to commit
suicide” A destructor is used to kill the objects that have been created by a
constructor. As like a constructor, destructor is a special member function that
resembles class name is preceded by a tilde (~).
- Objects are born on heap (through constructors)
- Killed on heap (through destructors by programmer)
- Commit suicide on heap (with application termination)
When the object is ready for garbage collection?
An object gets ready for Garbage Collection if and only if all of its references
are been completely un- referenced.

Real world example 1:


You are relaxed in your dining table having a burger with Pepsi Tin. Also you are
watching a Television. At your door steps you have a dustbin with collection of all
unused papers, burger covers, Tiffin packets, etc. (these are garbage collectable).
But remaining all items you are referred is not garbage collectable.

Municipal coordinator would come and collect only those objects from
dustbin placed outside your home. He will never collect TV, Tiffin you are
eating, Sofa, etc.

Municipal coordinator we are talking here is Garbage Collector.


Garbage Collector is not available in C++ as like Java/.NET. In C/C++ Memory allocation and
de allocation is done by programmer itself (using malloc, calloc, realloc, free functions).

Real world example 2:


Consider a teacher (object) placed on heap. Also some students (references)
are been referring to the teacher. The teacher can leave the class provided
every student is out of the class room. Even one student is referring him he
can’t leave the room. So, the Teacher is ready for garbage collection provided
all the references are unreferenced.
Memory Release is done implicitly by the compiler on closing of application by default.
But it can be achieved by a programmer by writing explicitly a destructor too.

What is Memory Leakage Problem?


It always suggested releasing the resources properly as it may lead to memory leakage.
It refers to a circumstance where we are unable to locate the address of reference
variable been allocated a certain amount of memory.

Obj13 - Program on Destructors – Objects Commit Suicide and Killed by programmer

Part A – Add Class BIRD explicitly into Solution


using System;
using [Link];
using [Link];
using [Link];

namespace Obj13
{
class Bird
{
private string name;

public Bird()
{
[Link]("Default Constructor: Object born");
}

public Bird(string val)


{
name = val;

[Link]("Parameterized Constructor: Object born");


}

~Bird()
{
[Link]( name + "Commit suicide-Deallocate by GC ");
}

public void Dispose()


{
[Link](this);

[Link](name + " Killed by programmer ");


/ Programmer need to dellocate state personally [Link] =

null;

}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj13
{
class Program
{
static void Main(string[] args)
{
Bird bird1, bird2, bird3;

bird1 = new Bird();

bird2 = new Bird("Parrot");

bird3 = new Bird("Peacock");

/ bird2 will be killed

[Link]();

/ Bird 2 and Bird 3 will commit suicide


}
}
}

Obj14 – Program on Complete Implementation of a class

Part A – Add Class REMOTECONTROL into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj14
{
class RemoteControl
{
// State

private int _volume;

// Behavior - Constructor - Initialize Objects

public RemoteControl()
{
// Default Constructor

[Link]("\n Default Constructor");


}

public RemoteControl(int value)


{
/ Parameterized Constructor

_volume = value;

[Link]("\n Default Constructor");


}

// Behavior - Property - Represent Current State of Object

public int Volume


{
get
{
return _volume;
}

set
{
_volume = value;
}
}
/ Behavior - Methods - Change The State of Object public void
VolumePlus()
{
_volume++;
}

public void VolumeMinus()


{
_volume--;

// Behavior - Destructor - Deallocates Objects

~RemoteControl()
{
[Link]("\n Object Commit Suicide");
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];
namespace Obj14
{
class Program
{
static void Main(string[] args)
{
RemoteControl rc = new RemoteControl();

[Link]("\n Input Volume Level "); [Link] =


[Link]([Link]());

[Link]("\n Current Volume Level \t " + [Link]);


[Link]();

[Link]("\n Current Volume Level \t " + [Link]);


[Link]();

[Link]("\n Current Volume Level \t " + [Link]);


}
}
}

Private Constructors

Constructors can be declared private, but that do not allow creating objects.

Pen p = new Pen (); will not be given access

Static Constructors

Constructors can be declared static, but that do not allow calling instance methods.

Hence I need to manage through PROPERTIES. It is mainly used to initialize static members.

Note: We don’t have any Static or Private destructors.

Differentiate Constructors and Destructors

1. Objects are born through constructors, whereas they are killed or commit
suicide through destructors.
2. Constructors can be declared static or private, whereas destructors can’t.
3. Constructors can take arguments, whereas destructors can’t.
4. Constructors can be overridden, whereas destructors can’t.

Differentiate Method and Constructor

1. Method may or may not return value, whereas constructor never returns.
2. Methods need to be called by programmer, whereas constructors are invoked.

OBJECT MEMORY ALLOCATION SEQUENCE

1. Class Loaded – A class is said to be loaded into heap memory, either static
members are accessed for the first time OR first object of the class is created.
2. Static members are loaded into memory.
3. Static constructor is executed.
4. Instance members are loaded into memory.
5. Instance Constructor is executed.
CLR try to invoke the main method even before the first instance or object had been
created.
Hence, the main method needs to be declared as static type.
FAQS

 What is the need of constructor?


 When should I prefer parameterized constructor?
 What is the default return type of constructor?
 Why can’t constructor return a value?
 What is copy constructor?
 Which constructor invokes by default?
 What happens if we make a constructor as private?
 What are static constructors?
 Differentiate constructor and destructor.
 Mention object life cycle.
 How objects are born?
 How object commit suicide?
 How objects are killed?
Objectives

Inheritance

Inheritance leads to “heredity” which involves Reusability and Extensibility.


Consider Basic and scientific calculator. The former don’t have the scientific functions as
in later. Later model will definitely includes the basic functionalities like plus, minus, etc
from former model that is referred by reusability, and also new features been added is
extensibility.

Inheritance is characterized by “IS-A” relationship like Dog is an Animal, Mango is a


Fruit, Blue is a Color, Bob is a cute girl, John is a good boy, etc.

Here Parent is Animal and Dog is a child (why), because every dog is an animal but
every animal can’t be dog.

Also every parent cannot have any kind of child. Like every student is a chair do not make
sense.

Class and Class Member is characterized by “HAS-A” relationship like Class


Student has a roll number, name, age, height, etc.

Here we have two types of classes – Super (BASE) and Sub (DERIVED) class.

C#.NET Supported forms of Inheritance


 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance

Single Inheritance

Multilevel Inheritance
S

P
44 | P a g e

Hierarchical Inheritance
L

S P T
Obj15 – Program on Simple Inheritance

Part A – Add class ANIMAL into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj15
{
class Animal
{
protected string _name;

public Animal()
{
[Link]("\n Animal - Base Class Constructor..");
}

public void AcceptName()


{
[Link]("\n May I Know Your Name?");
_name = [Link]();
}

public void DisplayName()


{
[Link]("\n My Name is " + _name);
}
}

// Carnivor is a Animal - Carnivor Extends Animal

class Carnivor : Animal


{

public Carnivor()
{
[Link]("\n Carnivor - Derive Class Constructor..");
}
public void Roar()
{
[Link](" I bark....");
}

public void Eat()


{
[Link](" I eat.....");
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj15
{
class Program
{
static void Main(string[] args)
{
Carnivor car = new Carnivor();

/ Access base class

members

[Link]();

[Link]();

/ Access derived class

members [Link]();

[Link]();
}
}
}
Obj16 – Program on Multilevel Inheritance

Part A – Add Class Employee Explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj16
{
class Employee
{
private string name;

public Employee()
{
[Link](" Employee Default Constructor...");
}

public void AcceptName()


{
[Link]("\n May I Know your Name?");
name = [Link]();
}
}

// Staff - Sub Class to Principal also Super Class to Principal

class Staff : Employee


{
public Staff()
{
[Link](" Staff Default Constructor...");
}
}

// Principal - Sub Class to Staff

class Principal : Staff


{
public Principal()
{
[Link](" Principal Default Constructor...");
}

public void Head()


{

[Link](" I am the head of instituition");


}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj17
{
class Program
{
static void Main(string[] args)
{
Principal p = new Principal();

/ Access Base Class and Derive Class

Members [Link]();

[Link]();

}
}
}

Obj18 – Program on Hierarchical Inheritance

Part A – Add Class ACCOUNT into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj18
{
class Account
{
protected int _balance;

public Account()
{
[Link]("\n Account - Base Class Constructor..");

public void CheckBalance()


{
[Link]("\n Account Balance \t " + _balance);
}
}

// SavingsAccount is an Account - SavingsAccount Extends Account

class SavingAccount : Account


{
public SavingAccount()
{
[Link]("\n SavingAccount - Class
Constructor..");
}

public void InitialDeposit()


{
_balance = 500;
}

// SalaryAccount is an Account - SalaryAccount Extends Account

class SalaryAccount : Account


{
public SalaryAccount()
{
[Link]("\n SalaryAccount - Class Constructor..");
}

public void InitialDeposit()


{
_balance = 0;
}
}
}
Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj19
{
class Program
{
static void Main(string[] args)
{
/ Access Saving Account Details

SavingAccount s = new

SavingAccount();

[Link]();
[Link]();

/ Access Salary Account Details

SalaryAccount p = new

SalaryAccount(); [Link]();

[Link]();
}
}
}

FAQS

 Define inheritance.
 Differentiate IS-A versus HAS-A relationship.
 What kind of inheritances supported in .NET?
 What should we implement in Base or super class?
 What should we implement in derived or sub class?
 Can a super class refer sub class reference variable?
 Can a sub class refer super class reference variable?
 Why C#.NET does not entertain multiple inheritances?
 What a super class object return?
 What a sub class object return?
Objectives
 Static Polymorphism – Function Overloading
 Static Polymorphism – Constructor Overloading
 Static Polymorphism – Operator Overloading
 Dynamic Polymorphism – Virtual Functions
 Abstract Class and Methods
 Concrete Methods
 Sealed Method
 Sealed Class
 Sequence of Constructors and destructors in inheritance

Polymorphism

Polymorphism refers to “multiple forms of an object with common functionality”.


Let’s understand with following two real time examples:

Example 1:
People do say that I am an all rounder – say Faculty and Singer. Hence my functionality
involves teaching and singing.
In current example, my form is changing from object Faculty to object Singer.
Also my functionality is changing from teaching to singing. Here we observe
different form and different functionality. Hence, it can’t be polymorphism.
Polymorphism entertains only change in form but not the change in functionality.

Example 2:
I can teach C language also C++ language. Here, object form is changing from C
faculty to C++ faculty, but both objects functionality teaching remains common.
Similarly, I can speak Hindi language also English language.

Polymorphism

Static Dynamic

Function Constructor Operator Virtual


Overloading Overloading Overloading Function
s

Static Polymorphism
Static Polymorphism refers to overloading member function, operator or
constructor. Overloading is always done only on the basis of function
arguments not on the basis of return types.
What is the need of overloading or static polymorphism?

Let’s consider a problem is given to two student’s John and Bob to solve. They will
provide to solutions SOL1 and SOL2. A programmer needs to declare two different
functions to represent them in a class. Also at run time two different stacks will be
created that leads heavy memory usage.

An alternative would be replacing SOL1 and SOL2 methods with only one SOL
member function name with two different versions. Doing this only one stack
created.
In C#.NET Static polymorphism can be implemented on the member
functions and constructors. C#.NET doesn’t support operator overloading
as like C++.

Rules to construct static polymorphism:


 Function Name can be same
 Function should be different in count of arguments with same data types
 Function can be same in count of arguments with different data types
 Function return types are not taken into consideration.
.
Obj20 - Program on Static Polymorphism - Function and Constructor Overloading

Part A – Add Class FIGURE explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj20
{
class Figure
{
private int _side;

private int _length, _breadth;

// Constructor Overloading

public Figure()
{
_side = 0;
_length = 0;
_breadth = 0;
}

public Figure(int side)


{
_side = side;
}

public Figure(int length, int breadth)


{
_length = length;
_breadth = breadth;
}

// Function Overloading Methods

public Int32 Area(int side)


{
return (_side * _side);
}

public Int32 Area(int length, int breadth)


{
return (_length * _breadth);
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];
namespace Obj20
{
class Program
{
static void Main(string[] args)
{
Figure f1 = new Figure(19);
Figure f2 = new Figure(19, 23);
[Link]("\n Area of circle is \t " + [Link](19).ToString());
[Link]("\n Area of rectangle is \t " +
[Link](19,23).ToString());
}
}
}

Operator Overloading
Overloading operators without changing the basic meaning of the operators. It
provides multi functioanility to the existing operators. Few operarors like new, sizeof,
cannot be overloaded. It is implicitly used in event handling, multicast delegates.

Obj21 - Program on Static Polymorphism - Operator Overloading

Part A – Add a class Number to the solution


using System;
using [Link];
using [Link];
using [Link];
namespace ConsoleApplication21
{
class Number
{
int val;

public void AcceptValue()


{
[Link]("Input value");
val = [Link]([Link]());
}

public static Number operator+(Number s, Number p)


{
Number z = new Number();
[Link] = [Link] + [Link];
return z;
}

// Operator function MINUS

public static Number operator -(Number s, Number p)


{
Number z = new Number();
[Link] = [Link] - [Link];
return z;
}
public static Number operator-(Number s)
{
Number z = new Number();
[Link] = -[Link];
return z;
}

// Operator function Multiply


public static Number operator *(Number s,Number p)
{
Number z = new Number();
[Link] = [Link] * [Link];
return z;
}

public static Number operator /(Number s, Number p)


{
Number z = new Number();
[Link] = [Link] / [Link];
return z;
}

public void DisplayValue()


{
[Link](" Value is " + val);
}
}
}

Part B – Program Class


using System;
using [Link];
using [Link];
using [Link];

namespace ConsoleApplication21
{
class Program
{
static void Main(string[] args)
{
Number s = new Number();
[Link]();

Number p = new Number();


[Link]();

Number z = new Number();


z = s / p;

[Link]();
z = -p;
[Link]();
}
}
}
Dynamic Polymorphism
Dynamic Polymorphism refers to overriding member function or constructor at run
time. In C++ dynamic polymorphism is achieved through virtual functions. Also C++
support pure virtual functions and abstract class.

C#.NET doesn’t support pure virtual instead it involves abstract methods.

C#.NET dynamic polymorphism involves Virtual Functions, Abstract class.

What is the need of dynamic polymorphism?

Consider two classes – Employee and Staff that having a common method Hello.
As usual we declare object of derived class Staff, then it would give respect to derived
version
Hello Method. But the programmer would like to like access both at his request.
In C++ as well C#.NET problem is solved by using Virtual functions.

Consider base and a derived class with common member function say hello. If you
define as usual derived class object and try to access the hello member function it calls
the derived class version itself. So, we have a problem to access the base class hello
member function. To resolve this problem C++/C#.NET provides a solution as Virtual
functions.

Obj22 – Program on Need of virtual functions

Part A – Add ANIMAL class explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj22
{
class Animal
{
public void Hello()
{
[Link]("Animal");
}
}

class Carnivor : Animal


{
public void Hello()
{
[Link]("Carnivor");
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj22
{
class Program
{
static void Main(string[] args)
{
Carnivor c = new Carnivor();

[Link](); // Calls only Derived Version


}
}
}

Obj23 – Program on Dynamic Polymorphism using Virtual function

Part A – Add class BIRD explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj23
{
class Bird
{
public virtual void Hello()
{
[Link]("\n I am Bird...");
}
}

class Peacock : Bird


{
override public void Hello()
{
[Link]("\n I am Peacock...");
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj23
{
class Program
{

static void Main(string[] args)


{

/ Declare Base Class only Reference

Variable Bird bref;

/ Set Base Class Reference variable to bird b

object bref = new Bird();

/ Invokes Bird - Hello Method

[Link]();

/ Set Base Class Reference variable to Peacock P

object bref = new Peacock();

// Invokes Peacock - Hello Method

[Link]();
}
}
}

Pure Virtual Functions

In the case of virtual function at any time only one version is active i.e. either base or
derived version. Hence it can be preferred only in a scenario when user would look
for both versions. Assuming a scenario in the case an end user would like to use only
the derived version at any point of time then virtual functions are not preferred.
Because, there would be always wastage of memory allocation for base class version
method as it’s been overridden by derived.

Hence by making virtual functions as do nothing or only signature based would solve it.
I mean make the base class version only signature or prototype based, just to override.
Hence, no memory or stack will be created for base class version.

In C++ it is solved by using Pure Virtual Functions (Virtual Function = 0).

In C#.NET it is solved using Abstract methods defined in an Abstract Class.

Abstract Class

An Abstract class is non-instant able class. It implies we cannot create objects of any
abstract class. It can also define as a class with a collection of at least one abstract
method.

An abstract class includes two types of methods – Abstract and Concrete Methods.
Abstract methods are without definitions and concrete with definitions. Abstract
method resemble as pure virtual function in context to C++.

The abstract class only provides signatures or prototypes for member functions
that are declared in class and further implemented in their derived classes. It
implies they are overridden in their respective derived classes.

Example:

Figure

Protected/Public
int l,b,s;
Public
Void area( ) = 0;
Void perimeter( ) = 0;

Square
Rectangle
Public
Public
Void area( );
Void area( );
Void perimeter( );
Void perimeter( );
Obj24 – Program on Abstract Class

Part A – Add class FIGURE explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj24
{
abstract class Figure
{

public Figure()
{
// No Effect Constructor
}

protected int side;

protected double radius;

/ Abstract Methods in Abstract

Class public abstract void Area();

public abstract void Perimeter();

/ Concrete Method in Abstract Class

public void Hi()


{
[Link]("\n Concrete : Hi Prati..");
}
}

// Square is a figure - Perfect Implementation of Abstract Class

class Square : Figure


{
public Square(int val)
{
side = val;
}

public override void Area()


{
[Link]("\n Area of Square is " + (side * side).ToString());
}

public override void Perimeter()


{
[Link]("\n Perimeter of Square is " + ( 4 * side).ToString());
}
}

// Circle is a Figure - Doesn't Override Perimeter Method - Hence become


Abstract abstract class Circle : Figure

{
public Circle(double val)
{

radius = val;
}

public override void Area()


{
[Link]("\n Area of Circle is " + ([Link] * radius * radius).ToString());
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj23
{
class Program
{
static void Main(string[] args)
{
/ Can't Create Object of Abstract Class - Figure

/ Figure f = new Figure();

Square s = new Square(19);


[Link]();
[Link]();
[Link]();
/ Can't Create Object of Converted Abstract Class -

Circle //Circle c = new Circle(); throws an error

}
}
}

Note: If the abstract methods are not implemented or overridden by the derived
classes then the respective derived class will also become abstract in nature. Hence it
also needs to apply as Abstract. In the above example Circle class didn’t implement
hence abstract.

Super and Sub Class Reference


A super class reference variable can refer to itself and its derived class. Because at
the time of reference, state is available for base as well derived version.

A sub class reference variable can refer only to itself, not to the super class. Because at
the time of reference, state is not available for derived version.

Obj25 – Program on Super and Sub Class Reference

Part A – Add Class Furniture

using System;
using [Link];
using [Link];
using [Link];

namespace Obj25
{
class Furniture
{
public Furniture()
{
[Link]("\n Furniture Class Constructor");
}

public void DisplayFurnitureName()


{
[Link]("\n I am a Furniture");
}
}

class Table : Furniture


{
public Table()
{
[Link]("\n Table Class Constructor");
}

public void DisplayTableName()


{
[Link]("\n I am a Table");
}
}
}

Part B – Program Class


using System;
using [Link];
using [Link];
using [Link];
namespace Obj25
{
class Program
{
static void Main(string[] args)
{
// Base Class Can Refer To Itself

Furniture f = new Furniture();


[Link]();

// Derive Class can Refer To Itself

Table t = new Table();


[Link]();

// Base Class can Refer To Derive Class

Furniture f1 = new Table();


[Link]();

/ Derive Class can't Refer To Base

Class //Table t1 = new Furniture();

}
}
}
Constructor and Destructor visit and execute sequence in
Inheritance Constructor

Visit Sequence : Derived Class followed by Base


Class

Execute Sequence : Base Class followed by Derived


Class

why? If in case derived class


constructor would like to
override the base class
constructor, to happen base
class need to execute earlier.
Destructor

Visit Sequence : Derived Class followed by Base Class


Execute Sequence : Derived Class followed by Base Class

why? By the runtime base class will not have state of derived class to de
allocate.

Obj26 – Program on Constructor and Destructor visit and execute

sequence Part A – Add Class Human Being into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj26
{
class HumanBeing
{
public HumanBeing()
{
[Link]("\n Base Class Constructor - HumanBeing ");
}

~HumanBeing()
{
[Link]("\n Base Class Destructor - HumanBeing ");
}

class Boy : HumanBeing


{
public Boy()
{
[Link]("\n Derive Class Constructor - Boy ");
}

~Boy()
{
[Link]("\n Derive Class Destructor - Boy ");
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];
namespace Obj26
{
class Program
{
/ Obj25 - Program on Constructor and Destructor
Sequence static void Main(string[] args)
{
Boy b = new Boy();
}
}
}

Sealed Class - A class which cannot be inherited further anymore is referred as sealed class.

Obj27 – Program on Sealed Class

Part A – Add Class Parent into Solution


using System;
using [Link];
using [Link];
using [Link];

namespace Obj27
{
sealed class Parent
{
public Parent()
{
[Link]("\n Parent Constructor...");
}
}

// Child Class Cannot Inherit Parent Class

class Child : Parent


{
public Child()
{
[Link]("\n Child Constructor...");
}
}
}

Part B – Program Class


using System;
using [Link];
using [Link];
using [Link];
namespace Obj27
{
class Program
{
static void Main(string[] args)
{
Child L = new Child();
// Sealed Class Cannot Inherited any more
}
}
}

Sealed Method – A overridden method which cannot be further overridden.

Obj28 – Program on Sealed Method

Part A – Add Class S into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj28
{
class S
{
public virtual void F()
{
[Link]("I have problem");
}
}

class P : S
{
// Final or Sealed - Override Method

sealed override public void F()


{
[Link]("Solution A");
}

Class T: P
{
// Cant OverRide above sealed method

sealed override public void F()


{
[Link]("Solution B try to replace A");
}
}

Part B – Program Class


using System;
using [Link];

using [Link];
using [Link];

namespace Obj28
{
class Program
{
static void Main(string[] args)
{
P p = new
P(); p.F();

// Cant Override as it's sealed

T t = new T();
t.F();
}
}
}
FAQS

1. What is static polymorphism?


2. What is dynamic polymorphism?
3. How to implement static polymorphism in C#.NET?
4. How to implement dynamic polymorphism in C#.NET?
5. What is the need of virtual functions?
6. When should a programmer opt virtual functions?
7. What is pure virtual or abstract functions?
8. What is an abstract class?
9. What is overridding?
10. What is early versus late binding?
11. Can I over ride constructor?
12. Can I overload main method?
13. Can I override main method?
14. What is sealed method?
15. What is sealed class?
16. Which class constructor is visted and executed first?
17. Which classdestructor is visted and executed first?
18. How to stop inheritance?
Objectives
 What is diamond problem?
 C#.Net multiple inheritance
 Differentiate Abstract class and Interface
 Base Keyword

Interface

C#.NET do not support Multiple inheritance due to the DIAMOND problem (C++Context) or
DDDas Deadly diamond of death (Java Context).

What is Diamond Problem?

FIGURE
virtual void area( ) = 0;

RECTANGLE SQUARE
area( ); area( );

USER

In the above example, we observe AREA abstract method is been implemented or


overridden by the two geometrical figures – Rectangle and Square in different
manner.
An end user would like to access the overidden method AREA from the base class FIGURE.
He fails to retrive as there ambuguity would raise. It’s not acceptable in C++.
This leads to DIAMOND problem.

Hence C#.Net and Java do not support Multiple inheritance, rather they
introduce an alternative INTERFACE in contrast to multiple inheritance.

In C#.NET we observe two types of Inheritance – Implementaion and Interface Inheritance.


Former refers to hire class members whereas later refers to override members.

Interface basically resembles to a class with following limitations:


- Cannot hold state as like class
- Can declare methods but access specifers private, public, protected not
allowed -Cannot declare objects for them as like class
-Cannot extend class
-Can Extend an Interface

A pure abstract class can also be treated as an Interface.


Differentiate Abstract Class and Interface
- Abstract class can hold state whereas, an Interface can’t hold state
-Abstract class can declare methods with any access specifier like private,
public or protected whereas, an Interface can’t do it.
-Abstract Class can extend any base class whereas, interface can’t extend any base
class.
-Abstract class methods may not be overridden whereas Interface must override.

Obj29 – Program on Interface

Part A – Add an Interface IFIGURE explictly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj29
{
// Declare an Interface

interface IFigure
{
void Area();
}

// Implement Interface IFigure

class Square : IFigure


{
private int _side;

public Square(int side)


{
_side = side;
}

public void Area()


{
[Link]("Area of Square is " + (_side * _side));
}
}

// Implement Interface IFigure


class Rectangle : IFigure
{
private int _length, _breadth;

public Rectangle(int length, int breadth)


{
_length = length;
_breadth = breadth;
}

public void Area()


{
[Link]("Area of Rectangle is " + (_breadth *_length));
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj29
{
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(19, 23);
[Link]();

Square s = new Square(19);


[Link]();
}
}
}

Obj30 – Program on Interface Inheritance

Part A – Add an Interface IPARENT into Solution

using System;
using [Link];
using [Link];
using [Link];
namespace Obj30
{
// Declare Inteface IPARENT

interface IParent
{
void Parent();
}

/ Declare Inreface ICHILD that Inherits from IPARENT


Interface interface IChild : IParent
{
void Child();
}

// Implement ICHILD Interface

class MyChild : IChild


{
public void Child()
{
[Link](" Hi.. I am child...");
}

public void Parent()


{
[Link](" Hi.. I am parent...");
}

// Implement IPARENT Interface

class MyParent : IParent


{
public void Parent()
{
[Link](" Hi.. I am parent...");
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];

namespace Obj30
{

class Program
{
static void Main(string[] args)
{
// Call Overridden Methods

MyChild mc = new MyChild();


[Link]();
[Link]();

MyParent mp = new MyParent();


[Link]();
}
}
}

Obj31 – Program on BASE keyword to access base class members

Part A – Add a class Animal explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj31
{
class Animal
{
public Animal()
{
[Link]("Animal cons..");
}
public void Hello()
{
[Link]("Hi.. I am non-vegeterian");
}
}
class Carnivor : Animal
{
public Carnivor()
{
/ Base keyword supports to call base class
members
[Link]();
}
}
}

Part B – Program Class

using System;
using [Link];
using [Link];
using [Link];
namespace Obj31
{
class Program
{
static void Main(string[] args)
{
Carnivor c = new Carnivor();
}
}
}

Note: Program Main Method can be overloaded but the compiler would execute only
the main method with string array argument only.

Program Main Method cannot be overridden as static members cannot be declared as


virtual.

Obj32 – Program on Passing Parameter Implicitly from derived to base class

constructor Part A – Add a class Bird Explicitly into Solution

using System;
using [Link];
using [Link];
using [Link];

namespace Obj32
{
class Bird
{
private string _name;

public Bird()
{
// No Implementation
}

public Bird(string name)


{
_name = name;
}

public void DisplayName()

{
[Link]("Hi.. I am "+_name);
}
}

class Sparrow : Bird


{
public Sparrow()
{
// No Implementation
}

public Sparrow(string name): base(name)


{
// No Implementation
}
}
}

Part B – Program Class


using System;
using [Link];
using [Link];
using [Link];
namespace Obj32
{
class Program
{
static void Main(string[] args)
{
Bird s = new Bird("Bird..");
[Link]();
Sparrow p = new Sparrow("sparrow");
[Link]();

}
}
}

Common questions

Powered by AI

Memory is allocated to data members each time a new object is created because each object may have a distinct state that needs individual memory allocation. In contrast, member functions represent shared behavior and are not reallocated for each object because their functionality does not change . Thus, their memory is allocated only once, which optimizes resource usage by placing them in global memory rather than the heap for each object .

In class design, data members represent the state of objects and are typically local variables that hold attributes specific to instances of the class, such as 'int id' in a student class . In contrast, member functions or methods represent the behavior or functionality associated with the objects, like the 'AcceptID()' function that allows a user to input a student's ID .

Static members are parts of a class that are shared among all instances of the class. They should be used when a resource or functionality needs to be shared across all objects, such as a count of all instances created ('count' variable) or a method calculating average class data like 'GetAvgHeight' . Static members are allocated memory only once and exist in global memory, making them highly efficient for shared data . They cannot access instance members directly because they do not reside in the heap memory .

Static methods in C# can only access other static methods because both reside in global memory and do not have access to instance-specific states that reside in heap memory. Since static methods are not instantiated with objects and do not hold object-specific memory references, they cannot address member variables of instance methods . This separation enforces that static members represent shared information or behavior applicable across all instances of a class, rather than instance-specific functionality .

In C#, access specifiers determine the visibility of class members. Private members are only accessible within the class itself, public members can be accessed from outside the class, and protected members can be accessed by derived classes . These specifiers help in implementing encapsulation by restricting direct access to certain parts of the class, following the principle that state is declared private and behavior defined public .

Virtual functions enable dynamic polymorphism in object-oriented programming by allowing derived class methods to override base class methods. This mechanism ensures that the appropriate method is called at runtime, depending on the object type that invokes it, rather than the reference type. This helps in scenarios where a base class reference is used to refer to derived class objects, enabling derived methods to override base methods . Virtual functions ensure that the most specific method related to the actual object type is executed .

An abstract class in object-oriented programming is a class that cannot be instantiated directly because it contains abstract methods that must be defined in its derived classes. These methods provide only the method signature without implementation, meant to be implemented by subclasses . Abstract classes are used as a blueprint, allowing standardization of behaviour across different subclasses while ensuring specific implementations in each . The inability to instantiate abstract classes enforces the requirement that the specification must be filled by a concrete implementation in derived classes .

The 'protected' access specifier should be used in class design when there is a need to grant access to class members to subclasses while preventing external classes from accessing them. This ensures that derived classes can access and extend particular functionalities or states of the base class while maintaining encapsulation . Using 'protected' effectively supports abstraction by allowing extendable design in class hierarchies and safeguarding member information from outside interference .

The scope resolution operator (::) in C++ is used to specify which class a member function belongs to, resolving ambiguity when multiple classes have functions with the same name. For instance, if both 'Customer' and 'Product' classes have a function named 'AcceptID', the operator helps identify which 'AcceptID' function should be invoked . This is particularly important in avoiding errors in complex programs where multiple function calls could potentially conflict due to similar naming .

A class becomes abstract in C# if it contains at least one abstract method, which is a method declared without a body and must be implemented by derived classes. Furthermore, if a derived class fails to implement the inherited abstract methods from its base, it also becomes abstract . Any abstract class cannot be instantiated directly as their primary role is to serve as a placeholder for subclasses that implement the abstract specifications .

You might also like