Understanding Object Oriented Programming Concepts
Understanding Object Oriented Programming Concepts
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.
OOPS Concepts
Object
Class
Data Abstraction
Data Encapsulation
Polymorphism
Inheritance
Object
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
Object Functionality
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).
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
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).
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.
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.
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.
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
People do say that I am an all rounder – say Faculty and Singer. Hence my functionality
involves teaching and singing.
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
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
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
class <class-name>
{
/ Class Data Members represent state
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”
Dot Operator
It is used to access the compatible member of the class along the object ([Link]).
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.
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj01
{
class Animal
{
/ Data Members - Represent State of
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;
a = new Animal();
[Link]();
[Link]();
}
}
}
(OR)
using System;
using [Link];
using [Link];
using [Link];
namespace Obj01
{
class Animal
{
/ Data Members - Represent State of
class Program
{
static void Main(string[] args)
{
/ Reference varible (yet to be
referred) Animal a;
a = new Animal();
/ Access the
behaviors
[Link]();
[Link]();
}
}
}
Obj02 - Program on Class - Access Specifiers Private, Public
using System;
using [Link];
using [Link];
using [Link];
namespace Obj02
{
class Cat
{
/ Data Members - Represent State of
objects
using System;
using [Link];
using [Link];
using [Link];
namespace Obj02
{
class Program
{
static void Main(string[] args)
{
// Object
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj03
{
class Student
{
// State
// Behavior
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;
s = new Student();
/ Static Definition
[Link](19);
[Link](“Parrot”);
/ [Link](19);
[Link]();
[Link]();
[Link]();
/ Dynamic
Definition
[Link]();
[Link]();
}
}
}
C#.NET Properties versus Methods
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj04
{
class Book
{
private int id;
// Properties
get
{
return id;
}
// Write Property
set
{
id = value;
}
}
public string BookName
{
// Read Property
get
{
return name;
}
// Write Property
set
{
name = value;
}
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj04
{
class Program
{
// Obj02 - Class with Read and Write Properties
[Link] = 1923;
// Accessing Properties
using System;
using [Link];
using [Link];
using [Link];
namespace Obj05
{
class RemoteControl
{
// State
public RemoteControl()
{
// Default Constructor
_volume = value;
set
{
_volume = value;
}
}
~RemoteControl()
{
[Link]("\n Object Commit Suicide");
}
}
}
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]();
[Link]();
using System;
using [Link];
using [Link];
using [Link];
namespace Obj06
{
class Book
{
private int id;
// Properties
get;
/ Write
Property set;
}
public string BookName
{
/ Read
Property get;
/ Write
Property set;
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj06
{
class Program
{
// Obj02 - Class with Read and Write Properties
[Link] = 1923;
// Accessing Properties
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.
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj07
{
class Item
{
private int id;
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();
[Link]();
[Link]();
}
}
}
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.
namespace Obj08
{
class Animal
{
/ Data Members - Represent State of
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];
MyPets[1] = new
Animal();
MyPets[2] = new
Animal();
for (int i = 0; i < [Link]; i++)
{
MyPets[i].AcceptName();
}
// Display Names
}
}
}
}
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
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.
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.
id = 19 id = 14 id = 23
name = prati name = sp name = sandy
S1 S2 S3
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.
S1 S2 S3
id = 19 id = 14 id = 23
name = prati name = name =
love sandy
Obj09 – Program on Static Data Members and Member Functions
using System;
using [Link];
using [Link];
using [Link];
namespace Obj09
{
class Student
{
private int id; // Specific Non-Static Attribute
// 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
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
}
}
}
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.
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?)
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj10
{
class Number
{
private int value;
using System;
using [Link];
using [Link];
using [Link];
namespace Obj10
{
class Program
{
// Obj10 - Program on Objects as Arguments
[Link]();
[Link]();
/ [Link](s, p);
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj11
{
class Number
{
private int value;
// Function Add with two object Arguments and class return type
return n3;
}
}
}
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]();
= [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).
[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.
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj12
{
class Bird
{
private string name;
public Bird()
{
[Link]("\n Default Constructor : Object born");
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj12
{
class Program
{
static void Main(string[] args)
{
Bird bird1, bird2, bird3,bird4;
/ 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.
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.
namespace Obj13
{
class Bird
{
private string name;
public Bird()
{
[Link]("Default Constructor: Object born");
}
~Bird()
{
[Link]( name + "Commit suicide-Deallocate by GC ");
}
null;
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj13
{
class Program
{
static void Main(string[] args)
{
Bird bird1, bird2, bird3;
[Link]();
using System;
using [Link];
using [Link];
using [Link];
namespace Obj14
{
class RemoteControl
{
// State
public RemoteControl()
{
// Default Constructor
_volume = value;
set
{
_volume = value;
}
}
/ Behavior - Methods - Change The State of Object public void
VolumePlus()
{
_volume++;
}
~RemoteControl()
{
[Link]("\n Object Commit Suicide");
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj14
{
class Program
{
static void Main(string[] args)
{
RemoteControl rc = new RemoteControl();
Private Constructors
Constructors can be declared private, but that do not allow creating objects.
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.
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.
1. Method may or may not return value, whereas constructor never returns.
2. Methods need to be called by programmer, whereas constructors are invoked.
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
Inheritance
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.
Here we have two types of classes – Super (BASE) and Sub (DERIVED) class.
Single Inheritance
Multilevel Inheritance
S
P
44 | P a g e
Hierarchical Inheritance
L
S P T
Obj15 – Program on Simple Inheritance
using System;
using [Link];
using [Link];
using [Link];
namespace Obj15
{
class Animal
{
protected string _name;
public Animal()
{
[Link]("\n Animal - Base Class Constructor..");
}
public Carnivor()
{
[Link]("\n Carnivor - Derive Class Constructor..");
}
public void Roar()
{
[Link](" I bark....");
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj15
{
class Program
{
static void Main(string[] args)
{
Carnivor car = new Carnivor();
members
[Link]();
[Link]();
members [Link]();
[Link]();
}
}
}
Obj16 – Program on Multilevel Inheritance
using System;
using [Link];
using [Link];
using [Link];
namespace Obj16
{
class Employee
{
private string name;
public Employee()
{
[Link](" Employee Default Constructor...");
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj17
{
class Program
{
static void Main(string[] args)
{
Principal p = new Principal();
Members [Link]();
[Link]();
}
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj18
{
class Account
{
protected int _balance;
public Account()
{
[Link]("\n Account - Base Class Constructor..");
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]();
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
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
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++.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj20
{
class Figure
{
private int _side;
// Constructor Overloading
public Figure()
{
_side = 0;
_length = 0;
_breadth = 0;
}
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.
namespace ConsoleApplication21
{
class Program
{
static void Main(string[] args)
{
Number s = new Number();
[Link]();
[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.
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj22
{
class Animal
{
public void Hello()
{
[Link]("Animal");
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj22
{
class Program
{
static void Main(string[] args)
{
Carnivor c = new Carnivor();
using System;
using [Link];
using [Link];
using [Link];
namespace Obj23
{
class Bird
{
public virtual void Hello()
{
[Link]("\n I am Bird...");
}
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj23
{
class Program
{
[Link]();
[Link]();
}
}
}
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.
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
using System;
using [Link];
using [Link];
using [Link];
namespace Obj24
{
abstract class Figure
{
public Figure()
{
// No Effect Constructor
}
{
public Circle(double val)
{
radius = val;
}
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
}
}
}
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.
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj25
{
class Furniture
{
public Furniture()
{
[Link]("\n Furniture Class Constructor");
}
}
}
}
Constructor and Destructor visit and execute sequence in
Inheritance Constructor
why? By the runtime base class will not have state of derived class to de
allocate.
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 ");
}
~Boy()
{
[Link]("\n Derive Class Destructor - Boy ");
}
}
}
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.
namespace Obj27
{
sealed class Parent
{
public Parent()
{
[Link]("\n Parent Constructor...");
}
}
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
Class T: P
{
// Cant OverRide above sealed method
using [Link];
using [Link];
namespace Obj28
{
class Program
{
static void Main(string[] args)
{
P p = new
P(); p.F();
T t = new T();
t.F();
}
}
}
FAQS
Interface
C#.NET do not support Multiple inheritance due to the DIAMOND problem (C++Context) or
DDDas Deadly diamond of death (Java Context).
FIGURE
virtual void area( ) = 0;
RECTANGLE SQUARE
area( ); area( );
USER
Hence C#.Net and Java do not support Multiple inheritance, rather they
introduce an alternative INTERFACE in contrast to multiple inheritance.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj29
{
// Declare an Interface
interface IFigure
{
void Area();
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj29
{
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(19, 23);
[Link]();
using System;
using [Link];
using [Link];
using [Link];
namespace Obj30
{
// Declare Inteface IPARENT
interface IParent
{
void Parent();
}
using System;
using [Link];
using [Link];
using [Link];
namespace Obj30
{
class Program
{
static void Main(string[] args)
{
// Call Overridden Methods
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]();
}
}
}
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.
using System;
using [Link];
using [Link];
using [Link];
namespace Obj32
{
class Bird
{
private string _name;
public Bird()
{
// No Implementation
}
{
[Link]("Hi.. I am "+_name);
}
}
}
}
}
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 .