0% found this document useful (0 votes)
5 views116 pages

Chapter 3

This document covers Object-Oriented Programming (OOP) concepts using Visual Basic, including definitions of classes and objects, constructors and destructors, and principles such as abstraction, encapsulation, inheritance, and polymorphism. It explains the structure of classes, the creation and usage of objects, and the importance of access modifiers and encapsulation in software design. Additionally, it provides examples and benefits of using OOP in programming.

Uploaded by

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

Chapter 3

This document covers Object-Oriented Programming (OOP) concepts using Visual Basic, including definitions of classes and objects, constructors and destructors, and principles such as abstraction, encapsulation, inheritance, and polymorphism. It explains the structure of classes, the creation and usage of objects, and the importance of access modifiers and encapsulation in software design. Additionally, it provides examples and benefits of using OOP in programming.

Uploaded by

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

CHAPTER -3

Windows Programming (VB)

Cosc 4045

Object Oriented Programming Concepts

Department of Computer Science

Done by:Ashenafi W(Msc)

11/21/2025 DONE BY: A.W 1


CONTENTS
1. Introduction
2. Classes & Objects
3. Constructors & Destructors
4. Functions / Methods in C#
5. Properties and Indexer in C#
6. Inheritance and Polymorphism
7. Interfaces

11/21/2025 ANDARGACHEW A. 2
INTRODUCTION:
OBJECT ORIENTED PROGRAMMING
Object-oriented programming (OOP) is a way
to organize and conceptualize a program as a
set of interacting objects.
The programmer defines the types of objects that will
exist.
The programmer creates object instances as they are
needed.
The programmer specifies how these various object
will communicate and interact with each other.

11/21/2025 ANDARGACHEW A. 3
WHAT IS OBJECT?
OOP is a method of programming that involves the
creation of intellectuals objects that model a business
problem we are trying to solve.
What is Object?
Object: A single software unit that combines attributes and
methods. It represents an entity in the real world.
Attribute: A "characteristic" of an object; like a variable associated with a
kind of object.
Method: A "behavior" of an object; like a function associated with a kind
of object.
Identifying an Object?
You can also think of other non physical things as objects:-
such as a bank account
A bank account is not something that can be physically touched but
intellectually we can consider a bank account to be an object.
11/21/2025 ANDARGACHEW A. 4
Examples
Dog
Attributes: breed, color, hungry, tired, etc.
Behaviors: eating, sleeping, etc.
Bank Account
Attributes: account number, owner, balance
Behaviors: withdraw, deposit

11/21/2025 ANDARGACHEW A. 5
OBJECTED ORIENTED PRINCIPLES
OOP contains the following fundamentals
principles
Abstraction
Allows us to consider complex ideas while ignoring irrelevant
detail that would confuse us.
Encapsulation
Allows us to hide data and controlling the visibility of the code.
Inheritance
Allows us to define general characteristics and operation of an
object and allow us to create more specialized versions of this
object
Polymorphism
Allows us to interact with an object as its generalized category
regardless of its more specialized category.
11/21/2025 ANDARGACHEW A. 6
EXAMPLE:
IDENTIFYING AND DESCRIBING
OBJECTS
Student Management System
Identify objects
Student – Teacher – Course - Class room – Registrar –
Schedule and more …
Describe the object: using attributes and behaviors
Student
oAttributes:
 Name, Id number, Date of Birth, Gender, department, section, batch, hair type,
favorite food, favorite book, favorite movie, registration date, marital status,
eye color, class year etc…
oBehaviors:
 Register, eat, sleep, run, walk, submit assignment, take exam, view grade,
attend class, attend lab, ask question, view assessment result, change
department etc….
11/21/2025 ANDARGACHEW A. 7
EXAMPLE:
APPLY OOP PRINCIPLES
Abstraction: ignoring irrelevant details
Student
oAttributes:
 Name, Id number, Date of Birth, Gender, department, section, batch, hair type, favorite food,
favorite book, favorite movie, registration date, marital status, eye color, class year
oBehaviors:
 Register, eat, sleep, submit assignment, take exam, view grade, attend class, attend lab, ask
question, view assessment result, run, walk, change department

Encapsulation: hiding the data implementation details (sake of


simplicity and security)
Student
oAttributes:
 Name, Id number, Date of Birth, Gender, department, section, registration date, marital status,
class year.
oBehaviors:
 Register, submit assignment, take exam, view grade, attend class, attend lab, ask question,
view assessment result, change department

11/21/2025 ANDARGACHEW A. 8
Inheritance: creating general and specialized version of
objects
Person
Person
oAttributes:
 Name, Id number, Date of Birth, Gender,
registration date, marital status.
Student Student Teacher
oAttributes:
 department, section, class year.
Teacher
oAttributes:
 salary, years of experience, specialized subject.

11/21/2025 ANDARGACHEW A. 9
Polymorphism: the ability of a single interface to be used to
refer to multiple implementations of a particular behavior
Person
oBehavior:
 Register Person
Student
oBehavior:
 Register
Teacher Student Teacher
oBehavior:
 Register

11/21/2025 ANDARGACHEW A. 10
11/21/2025 ANDARGACHEW A. 11
BENEFITS OF OOP APPROACH
Better abstraction
Modeling information and behavior together
Better maintainability
More comprehensible, less fragile software
Better usability
Classes as encapsulated components that can be
used in other systems

11/21/2025 ANDARGACHEW A. 12
CLASSES AND OBJECTS
What is Classes?
The definitions of the attributes and methods of an object are
organized into a class.
Thus, a class is the generic definition for a set of similar
objects (i.e. Person as a generic definition for different
persons)
A class is an abstract description of a set of objects.
A class can be thought of as a template used to create a set
of objects. (A blue print to create (instantiate) an object)
We actually write code for a class, not object

11/21/2025 ANDARGACHEW A. 13
Object : an instances of the class.
Every instance of the same class will have the same set of
attributes;
Every object has the same attributes but,
Each instance will have its own distinct values for those attributes.

11/21/2025 ANDARGACHEW A. 14
BANK EXAMPLE
class: Account

The "account" class describes number:


the attributes and behaviors of balance:
bank accounts. deposit()

The “account” class defines withdraw()

two state variables (account


number and balance) and two
methods (deposit and
withdraw).
11/21/2025 ANDARGACHEW A. 15
BANK EXAMPLE – THREE OBJECTS Instance #1

number: 054

When the program runs there balance: $19

Instance #2
will be many instances of the
number: 712
account class.
balance: $240

Each instance will have its own Instance #3

account number and balance number: 036

(object state) balance: $941

11/21/2025 ANDARGACHEW A. 16
VARIABLES AND METHODS
Instance Variable and Instance Methods
A state-variables/ methods that are associated with
the one instance of a class – instance
variable/method.
Instance variables and instance methods can be public or
private.
It is necessary to instantiate (create an instance of) a class to
use its instance variables and instance methods.

11/21/2025 ANDARGACHEW A. 17
Class Variables and Class Methods
In addition to instance variables and instance
methods, classes can also define class methods and
class variables.
These are attributes and behaviors associated with the class
as a whole, not any one instance.
Class variables and class methods can be public or private.
It is not necessary to instantiate a class to use it’s class
variables and class methods.

11/21/2025 ANDARGACHEW A. 18
Note: Class variables and methods are declared
with the static keyword in C#.
A class variable defines an attribute of an entire class.
In contrast, an instance variable defines an attribute of instance
a single instance of a class. variable
s

Account
class
variable
count: 3 num: 054 num: 712 num: 036
bal: $19 bal: $240 bal: $941
printCount
Class ()
method
11/21/2025 ANDARGACHEW A. 19
ACCESS MODIFIERS
All types and type members have an
accessibility level, which controls whether they
can be used from other code in your assembly
or other assemblies.
Access modifiers(or access specifies) are keywords
that set the accessibility of classes, methods, and
other members
public access modifiers
The type or member can be accessed by any other
code in the same assembly or another assembly that
references it.
11/21/2025 ANDARGACHEW A. 20
private access modifiers
The type or member can be accessed only by code in the
same class
protected access modifiers
The type or member can be accessed only by code in the
same class, or in a class that is derived from that class
internal access modifiers
The type or member can be accessed by any code in the
same assembly, but not from another assembly.
An assembly is a file that is automatically generated by
the compiler upon successful compilation of every .NET
application. It can be either a Dynamic Link Library or an
executable file
11/21/2025 ANDARGACHEW A. 21
Defaults access modifiers
The default access modifier for a class is internal
The default access modifier for a class member is
private
protected internal access modifiers
The type or member can be accessed by any code in
the assembly in which it is declared, or from within a
derived class in another assembly

11/21/2025 ANDARGACHEW A. 22
ENCAPSULATION
When classes are defined, programmers can
specify that certain methods or state variables
remain hidden inside the class.
These variables and methods are accessible from
within the class, but not accessible outside it.
The combination of collecting all the attributes of an
object into a single class definition, combined with
the ability to hide some definitions and type
information within the class, is known as
encapsulation.
11/21/2025 ANDARGACHEW A. 23
GRAPHICAL MODEL OF AN
OBJECT Instance balance()
variables

withdraw() theBalance deposit()


acctNumber

accountNumber()
Methods

State variables make up the nucleus of the


object. Methods surround and hide
(encapsulate) the state variables from the
11/21/2025
rest of the program. ANDARGACHEW A. 24
OOP encapsulation is roughly analogous to
only allowing a user to access data in a
database via predefined stored procedures.
Users can access the data, but not directly and
without having to have direct knowledge of its
structure.

11/21/2025 ANDARGACHEW A. 25
CLASS & OBJECT IMPLEMENTATION
Defining a Class
In object oriented programming, a class defines
certain properties, fields, events, method etc.
A class defines the kinds of data and the functionality their
objects will have.
A class definition starts with the keyword class
followed by the class name; and the class body
enclosed by a pair of curly braces.

11/21/2025 ANDARGACHEW A. 26
Following is the general format of class
definition
<access specifier> class class_name {
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2; ...
<access specifier> <return type> method1(parameter_list)
{
// method body
}
}
 Example public class Customer {
// Fields, properties, methods
and events go here...
}

11/21/2025 ANDARGACHEW A. 27
Note
Access specifiers specify the access rules for the
members as well as the class itself.
If not mentioned, then the default access specifier for
a class type is internal.
Default access for the members is private.

11/21/2025 ANDARGACHEW A. 28
Creating Objects
Objects can be created by using the new keyword followed by
the name of the class that the object will be based on, like this
Customer cust1= new Customer();
When an instance of a class is created, a reference to the
object is passed back to the programmer.
In the previous example, cust1 is a reference to an object that is based
on Customer
This reference refers to the new object but does not contain the object
data itself.

11/21/2025 ANDARGACHEW A. 29
30

Declaring Object reference


Class Declaration variables
Circle myCircle;
class Circle
{ Creating Objects
double radius = 1.0;
myCircle=new Circle();
double findArea(){
return radius * radius *
3.14159; …in a single step
} Circle myCircle=new Circle();
}
11/21/2025
ANDARGACHEW A.
Accessing Objects
Referencing the object’s data
[Link]
[Link]
Invoking the object’s method:
[Link]
[Link]()

11/21/2025 ANDARGACHEW A. 31
Defining Method
A method can be defined using the following templates
{modifier} {return type} MethodName ({parameters})
{
// body
}
Example
public void MyMethod(int parameter1, string parameter2)
{
// write your method code here..
}

11/21/2025 ANDARGACHEW A. 32
Defining Field
 Field is a class level variable that can holds a value.
 Generally field members should have a private access modifier and
used with a property.
 Member fields are the attributes of an object (from design
perspective) and they are kept private to implement
encapsulation.
 These variables can only be accessed using the public
member functions.

11/21/2025 ANDARGACHEW A. 33
Static Members of a C# class
We can define class members as static using
the static keyword.
When we declare a member of a class as static, it means no
matter how many objects of the class are created, there is
only one copy of the static member.
The keyword static implies that only one instance of
the member exists for a class.
Static variables are used for defining constants because their
values can be retrieved by invoking the class without creating
an instance of it.
Static variables can be initialized outside the member
function or class definition.
11/21/2025 ANDARGACHEW A. 34
Static Method/Function
Sometimes a method performs a task that does not depend on
the contents of any object.
Such a method applies to the class in which it’s declared as a whole and is
known as a static method.
To declare a method as static, place the keyword static before the
return type in the method’s declaration.
You call any static method by specifying the name of the class in which
the method is declared, followed by the member access (.) operator and
the method name, as in
[Link]( arguments )
eg: [Link]( 900.0 )
 Such functions can access only static variables.
11/21/2025 ANDARGACHEW A. 35
Rules for Static Class
Static classes cannot be instantiated.
All the members of a static class must be static;
otherwise the compiler will give an error.
A static class can contain static variables, static
methods, static properties, static operators, static
events, and static constructors.
A static class cannot contain instance members and
constructors.
Indexers and destructors cannot be static
11/21/2025 ANDARGACHEW A. 36
var cannot be used to define static members. You
must specify a type of member explicitly after
the static keyword.
Static classes are sealed class and therefore, cannot
be inherited.
A static class cannot inherit from other classes.
Static class members can be accessed using
[Link].
A static class remains in memory for the lifetime of
the application domain in which your program
resides.
11/21/2025 ANDARGACHEW A. 37
CONSTRUCTORS
A class constructor is a special member method
of a class that is executed whenever we create new
objects of that class.
A constructor has exactly the same name as that of class
and it does not have any return type.
A class can have parameterized or parameter less
constructors.
The constructor will be called when you create an
instance of a class.
Constructors can be defined by using an access modifier
and class name: <access modifiers> <class name>(){ }
11/21/2025 ANDARGACHEW A. 38
Important points to remember about
Constructors
A constructor cannot be abstract, final, and
Synchronized.
Within a class, you can create only one static constructor.
A static constructor cannot be a parameterized constructor.
Constructor of a class must have the same name as the class
name in which it resides.
A constructor doesn’t have any return type, not even
void.
A class can have any number of constructors.
11/21/2025 ANDARGACHEW A. 39
Types of Constructors
Default Constructor
A constructor with no parameters is called a default constructor
(initializes all numeric fields to zero and all string and object fields
to null inside a class)
Parameterized Constructor
A constructor have at least one parameter is called a
parameterized constructor. (helps you to assign initial value to an
object at the time of its creation )
Copy Constructor
This constructor will creates an object by copying variables from
another object. (initialize a new instance to the values of an
existing instance)
11/21/2025 ANDARGACHEW A. 40
class Employee //Parameterized Constructor Employee u1= new Employee();
{ public Employee(string a, Employee u2 = new
string b) Employee(“Meron”,”AA”);
private name, location;
{ Employee u3 = new
//Default Constructor Employee(u1) ;
name = a;
public Employee()
location = b;
{ }
name = "Alex Len"; public Employee(Employee s)
location = "San {
Francisco";
name= [Link];
} location= [Link]
}

11/21/2025
} ANDARGACHEW A. 41
DESTRUCTORS
A destructor is a special member function of a
class that is executed whenever an object of its
class goes out of scope.
A destructor has exactly the same name as that of
the class with a prefixed tilde (~) and it can neither
return a value nor can it take any parameters.
Destructor can be very useful for releasing
memory resources before exiting the program.
Destructors cannot be inherited or overloaded.
11/21/2025 ANDARGACHEW A. 42
Important Points:
A Destructor is unique to its class i.e. there cannot be
more than one destructor in a class.
A Destructor has no return type and has exactly the same
name as the class name (Including the same case).
It is distinguished apart from a constructor because of the Tilde
symbol (~) prefixed to its name.
A Destructor does not accept any parameters and
modifiers.
It cannot be defined in Structures. It is only used with classes.
It cannot be overloaded or inherited.
It is called when the program exits.
The destructor will invoke automatically, whenever an
instance of class is no longer needed.
11/21/2025 ANDARGACHEW A. 43
EXERCISE 1:
Create a class "House", with an attribute
“length”, “width”, "area", a constructor that sets
the attributes, and a method "ShowData" to
display "I am a house, my area is xxx m2
(instead of xxx, it will show the real surface).
Write a second class to test your House class:
TestClass.
The second class should allow the user to input
length and width of the house.
Display the area of the house using ShowData
11/21/2025 ANDARGACHEW A. 44
EXERCISE 2:
Create a class “Person", with an attribute
“name” and “age”, a constructor that sets the
attributes, and a method “PrintData" to display
“Name: xxxx and Age: xxxx. (instead of xxxx,
it will show the real name and age).
Write a second class to test your Person class:
TestClass.
Create two instances of the "Person" class, set their
attributes using the constructor.
Print persons’ name and age using PrintData method.
11/21/2025 ANDARGACHEW A. 45
EXERCISE 3:
Write a C# program that accept two integers and
return true if either one is 5 or their sum or
difference is 5.
Class names: Program3, TestProgram3(Main method)
Attributes: number1 and number2
Method: checkIf5
Sample Output:
Enter the first number: 5
Enter the second number: 3
True

Enter the first number: 3


Enter the second number: 4
False
11/21/2025 ANDARGACHEW A. 46
EXERCISE 4:
Create a class called ‘Circle’, which contains the
following:
Two private instance variables: radius (of the type double)
and color (of the type String), with default value of 1.0
and "red", respectively (use the constructors to set the
values).
Two overloaded constructors - a default constructor with
no argument, and a constructor which takes a double
argument for radius.
Two public methods: getPerimeter() and getArea(), which
return the perimeter(2πr) and area(πr2) of this instance,
respectively.
11/21/2025 ANDARGACHEW A. 47
EXERCISE 5:
Write a C# program to check if it is possible to add two
integers to get the third integer from three given
integers
Class names: Program5, TestProgram5(Main method)
Attributes: number1 , number2 and number3
Method: checkIfPossible
Sample Output:
Enter the first number: 5
Enter the second number: 3
Enter the third number: 2
True

Enter the first number: 3


Enter the second number: 4
Enter the third number: 5
False
11/21/2025 ANDARGACHEW A. 48
EXERCISE 6:
Write a C# program to check if two or more non-
negative given integers have the same rightmost digit.
Class names: Program6 , TestProgram6(Main method)
Attributes: number1 , number2 and number3
Method: checkRigtmostDigit
Sample Output:
Enter the first number: 50
Enter the second number: 30
Enter the third number: 20
True

Enter the first number: 31


Enter the second number: 43
Enter the third number: 52
False

11/21/2025 ANDARGACHEW A. 49
EXERCISE 7:
Write a C# program to calculate the area of the
rectangle.
Class names: Program7 , TestProgram7(Main method)
Attributes: length, width
Method: caculateArea, getLength, getWidth, setLength,
setWidth
Sample Output:
Enter the length of the rectangle: 6
Enter the width of the rectangle: 7
******************************
The length of the rectangle is: 6
The width of the rectangle is: 7
11/21/2025 ANDARGACHEW A. 50
EXERCISE 8:
Write a C# program to check which number
nearest to the value 100 among two given
integers. Return 0 if the two numbers are
equal.
Class names: Program8 , TestProgram8(Main method)
Attributes: number1, number2
Method: checkNearest
Sample Output:
Enter the first number: 89
Enter the second number: 92
92
11/21/2025 ANDARGACHEW A. 51
PROPERTIES IN C#
Properties are also known as the smart fields
in C#
They are the extensions of the C# data fields
In a class we declare the data fields as private
and will provide the public SET/GET methods to
access the data fields
The access modifier can be private, public, protected
or internal
The return type can be any valid C# data type
11/21/2025 ANDARGACHEW A. 52
Properties : get and set Accessors
 Properties contain
 getters (get{}) to retrieve the value of the underlying field and
 setters (set{}) to set the value of the underlying field
Syntax of Properties
<acces_modifier> <return_type> <property_name>
{
get
{}
set
{}
}

11/21/2025 ANDARGACHEW A. 53
EXAMPLE
private int length;
public int Length
{
get
{
return length;
}
set
{
length = value;
}
}

11/21/2025 ANDARGACHEW A. 54
By convention, we name each property with the
capitalized name of the instance variable that it
manipulates.
e.g., Length is the property that represents instance variable
length - C# is case sensitive, so these are distinct
identifiers.
A private field which cannot be accessed
directly. It will only be accessed via a Property.
Calling a getter or a setter in C#
[Link]
Getters and setters let you treat the values like public
properties.
11/21/2025 ANDARGACHEW A. 55
We can also apply some additional logic in get and set, as in the below
example.
public int Length
{
get { return length/2; }
set {
if (value > 0)
length = value;
else
length = 0;
}
}
11/21/2025 ANDARGACHEW A. 56
Auto-implemented Property
property declaration has been made easy if
you don't want to apply some logic in get or
set.
The following is an example of an auto-
implemented property:
public int Length{ get; set; }

11/21/2025 ANDARGACHEW A. 57
INDEXERS IN C#
An indexer allows an instance of a class to be
indexed as an array.
If the user will define an indexer for a class, then the
class will behave like a virtual array.
Array access operator i.e ([ ]) is used to access the
instance of the class which uses an indexer.
A user can retrieve or set the indexed value without
pointing an instance or a type member.
Indexers are almost similar to the Properties.
The main difference between Indexers and Properties is
that the accessors of the Indexers will take parameters.
11/21/2025 ANDARGACHEW A. 58
Syntax
[access_modifier] [return_type] this [argument_list]
{
get
{
// get block code
}
set
{
// set block code
}
}

11/21/2025 ANDARGACHEW A. 59
Important Points About Indexers:
There are two types of Indexers i.e. One Dimensional
Indexer & Multi-Dimensional Indexer
Indexers can be overloaded.
Indexers are also known as the Smart
Arrays or Parameterized Property in C#.
This enables the object to be indexed in a similar way to
arrays.
A set accessor will always assign the value while the get accessor
will return the value.
“this” keyword is always used to declare an indexer.
To define the value being assigned by the set indexer, ”value”
keyword is used.
Indexer can’t be a static member as it is an instance
member of the class.
11/21/2025 ANDARGACHEW A. 60
EXAMPLE

11/21/2025 ANDARGACHEW A. 61
11/21/2025 ANDARGACHEW A. 62
EXERCISE 9:
Create a Month class that has a single data member of
(private) month number.
Create a public properties for month number variable.
Include a member method that returns the name of the month
and another method that returns the number of days in the
month.
The DisplayDetail( ) method should return the name and
number of days.
Write a second class to test your Month class
(TestMonth).
The second class should allow the user to input a month
number.
Display the name of the month associated with the number
entered and the number of days in that month. For this ANDARGACHEW A.
11/21/2025 63
EXERCISES 10:
1. Define a class Student, which contains the
following information about students: full
name, course, subject, university, e-mail and
phone number.
2. Declare several constructors for the class
Student, which have different lists of
parameters (for complete information about a
student or part of it).
3. Modify the current source code of Student
class so as to encapsulate the data in the
11/21/2025 ANDARGACHEW A. 64
4. Add a static field for the class Student, which
holds the number of created objects of this
class.
5. Add a method in the class Student, which
displays complete information about the
student.
6. Write a class StudentTest, which
demonstrates the functionality of the class
Student.
11/21/2025 ANDARGACHEW A. 65
INHERITANCE
Inheritance allows a software developer to derive a
new class from an existing one.
The existing class is called the parent, super, or base class.
The derived class is called a child or subclass.
The child inherits characteristics of the parent.
The child has special rights to the parents methods and
data.
Public access like any one else
Protected access available only to child classes (and their
descendants).
The child has its own unique behaviors and data.
11/21/2025 ANDARGACHEW A. 66
The advantage of making a new class a
subclass is that it will inherit attributes and
methods of its parent class (also called the
super-class).
Subclasses extend existing classes in three
ways:
By defining new (additional) attributes and methods.
By overriding (changing the behavior) existing
attributes and methods.
By hiding existing attributes and methods.
11/21/2025 ANDARGACHEW A. 67
EXAMPLE: EXTENDING EXISTING
CLASSES

11/21/2025 ANDARGACHEW A. 68
11/21/2025 ANDARGACHEW A. 69
EXAMPLES: BASE CLASSES AND
DERIVED CLASSES
Base class Derived classes
Student GraduateStudent
UndergraduateStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan
MortgageLoan
Employee FacultyMember
StaffMember
Account CheckingAccount
SavingsAccount

11/21/2025 ANDARGACHEW A. 70
Inheritance should create an is-a relationship,
meaning the child is a more specific version of the
parent.
The ability to use inheritance makes programs
easier to write, less error-prone, and easier to
understand
Terminology
Super (Base) class: a class that is used as a basis for
inheritance
Subclass (derived/extended): a class that inherits from a
base class.
11/21/2025 ANDARGACHEW A. 71
Extending Classes
When you create a class that is an extension or child of
another class, you use a single colon (:) between the derived
class name and its base class name
Inheritance works in one direction
The keyword protected provides you with an
intermediate level of security
A protected data field or method can be used within its own
class or in any classes extended from that class, but it cannot
be used by “outside” classes
C# and Java support single inheritance, meaning that
a derived class can have only one parent class.
11/21/2025 ANDARGACHEW A. 72
Declaring a derived class
Define a new class DerivedClass which extends
BaseClass
class BaseClass
{
// class contents
}
class DerivedClass : BaseClass
{
// class contents
}
11/21/2025 ANDARGACHEW A. 73
EXAMPLE: INHERITANCE

11/21/2025 ANDARGACHEW A. 74
Output

11/21/2025 ANDARGACHEW A. 75
Overriding Methods
A child class can override the definition of an
inherited method in favor of its own
That is, a child can redefine a method that it inherits from its
parent
The new method must have the same signature as
the parent's method, but can have a different
implementation.
The type of the object executing the method determines
which version of the method is invoked.

11/21/2025 ANDARGACHEW A. 76
Derived classes can also override inherited
members by providing an alternate
implementation.
In order to be able to override a member, the
member in the base class must be marked with the
virtual keyword.
By default, base class members are not
marked as virtual and cannot be overridden.
Using the same method name to indicate
different implementations is called
11/21/2025 ANDARGACHEW A. 77
Method Overriding (virtual and override keyword)
 In C#, for overriding the base class method in derived class, you have to
declare base class method as virtual and derived class method
as override as shown below:
class A
{
public virtual void Test()
{
[Link]("A::Test()");
}
}
class B : A
{
public override void Test()
{
[Link]("B::Test()");
}
}
11/21/2025 ANDARGACHEW A. 78
Note
1. The virtual keyword is used to modify a method,
property, indexer, or event declared in the base
class and allow it to be overridden in the derived
class.
2. The override keyword is used to extend or modify
a virtual/abstract method, property, indexer, or
event of base class into derived class.
3. The new keyword is used to hide a method,
property, indexer, or event of base class into
derived class
11/21/2025 ANDARGACHEW A. 79
References and inheritance
An object reference can refer to an object of its class, or
to an object of any class derived fromHoliday
it by day;
inheritance.
day = new Holiday();
Dynamic Binding …
day = new Christmas();
A polymorphic reference is one which can refer to
different types of objects at different times. It morphs!
The type of the actual instance, not the declared type,
determines which method is invoked.
Polymorphic references are therefore resolved at run-
time, not during compilation.
This is called dynamic binding.

11/21/2025 ANDARGACHEW A. 80
11/21/2025 ANDARGACHEW A. 81
Constructor Chaining in C#
Constructor chaining enables the calling of one
constructor from another within the same class or
between the base and derived classes.
It allows the initialization logic defined in one constructor to be
reused by other constructors, reducing code duplication and
improving maintainability.
In C#, constructor chaining is achieved using this and
base keywords.
The base keyword is used to call a constructor in the base class.
oSpecify which base-class constructor should be called when creating
instances of the derived class.
The this keyword is used to call another constructor in the same
11/21/2025 ANDARGACHEW A. 82
11/21/2025 ANDARGACHEW A. 83
11/21/2025 ANDARGACHEW A. 84
How do access base class methods from a
Subclass?
The base keyword is used to access members of the
base class from within a derived class:
Call a method on the base class that has been overridden by
another method.
A base class access is permitted only in a constructor, an
instance method, or an instance property accessor.
It is an error to use the base keyword from
within a static method.
11/21/2025 ANDARGACHEW A. 85
11/21/2025 ANDARGACHEW A. 86
EXERCISE-11
Define a class Human with properties "first
name" and "last name". Define the class Student
inheriting Human, which has the property
"mark". Define the class Worker inheriting
Human with the property "wage" and "hours
worked". Implement a "calculate hourly wage"
method, which calculates a worker’s hourly pay
rate based on wage and hours worked. Write
the corresponding constructors and
encapsulate all data in properties.
11/21/2025 ANDARGACHEW A. 87
11/21/2025 ANDARGACHEW A. 88
EXERCISE-12
Create a class named 'Member' having the
following members: Name, Age, Phone number,
Address, and Salary
It also has a method named ‘PrintSalary' which prints the
salary of the members.
Two classes 'Employee' and 'Manager' inherits the
'Member' class.
The 'Employee' and 'Manager' classes have data members
'specialization' and 'department' respectively.
Now, assign name, age, phone number, address
and salary to an employee and a manager by
making an object of both of these classes and print
the same.
11/21/2025 ANDARGACHEW A. 89
POLYMORPHISM
This is the ability of an object to perform in a
wide variety of ways. There are two types:
Static polymorphism (compile time). You can achieve
static polymorphism through function overloading
and operator overloading.
Dynamic polymorphism (runtime time). You can
obtain this type through executing function
overriding.

11/21/2025 ANDARGACHEW A. 90
Static Polymorphism
The mechanism of linking a function with an object
during compile time is called early binding.
It is also called static binding.
C# provides two techniques to implement static
polymorphism. They are −
Function/Method overloading
Operator overloading

11/21/2025 ANDARGACHEW A. 91
Method Overloading
It is the ability to redefine a function/method in more
than one form.
A user can implement method overloading by defining two or
more methods in a class sharing the same name.
C# can distinguish the methods with different
method signatures.
i.e. the methods can have the same name but with different
parameters list (i.e. the number of the parameters, order of
the parameters, and data types of the parameters) within the
same class.
11/21/2025 ANDARGACHEW A. 92
Overloaded methods are differentiated based on the
number and type of the parameters passed as
arguments to the methods.
You can not define more than one method with the same
name, Order and the type of the arguments. (It would be
compiler error.)
The compiler does not consider the return type while
differentiating the overloaded method.
You cannot declare two methods with the same
signature and different return type.
11/21/2025 ANDARGACHEW A. 93
Different ways of doing overloading methods-
Method overloading can be done by changing:
1. The number of parameters in two methods.
2. The data types of the parameters of methods.
3. The order of the parameters of methods
Why do we need Method Overloading ?
If we need to do the same kind of the operation in
different ways i.e. for different inputs.

11/21/2025 ANDARGACHEW A. 94
OUTPUT
Printing int: 5
Printing float:
500.263
Printing string:Hello
C++

11/21/2025 ANDARGACHEW A. 95
Operator Overloading
We can redefine or overload most of the built-in
operators available in C#.
Thus a programmer can use operators with user-defined
types as well.
Overloaded operators are functions with special
names the keyword operator followed by the symbol
for the operator being defined.
Similar to any other function, an overloaded operator has a
return type and a parameter list.
One of the parameters of the given operator must be the
containing type
o "Containing" refers to the class that the declaration is currently in
11/21/2025 ANDARGACHEW A. 96
Syntax
access_specifier return_type operator Operator_symbol (parameters)
{ // Code }
Example
public static Box operator+ (Box b, Box c) {
Box box = new Box();
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return box;
}
The above function implements the addition operator (+) for a user-
defined class Box. It adds the attributes of two Box objects and
returns the resultant Box object.

11/21/2025 ANDARGACHEW A. 97
Overloadable and Non-Overloadable Operators
The following table describes the overload ability of the
operators
No. in C# &: Description
Operators
1 +, -, !, ~, ++, -- : These unary operators take one operand and
can be overloaded.
2 +, -, *, /, % : These binary operators take one operand and can be
overloaded.
3 ==, !=, <, >, <=, >= : The comparison operators can be
overloaded.
4 &&, || : The conditional logical operators cannot be overloaded
directly.
5
11/21/2025 +=, -=, *=, /=, %= : The assignment operators cannot be ANDARGACHEW A. 98
Dynamic Polymorphism
Dynamic polymorphism is implemented by abstract
classes and virtual methods.
C# allows you to create abstract classes that are used
to provide partial class implementation of an
interface.
Implementation is completed when a derived class inherits
from it.

11/21/2025 ANDARGACHEW A. 99
Abstract Classes
An abstract class is one from which you cannot create
any concrete objects, but from which you can inherit
An abstract method has no method statements;
Any class derived from a class containing an abstract
method must override the abstract method by
providing a body for it
When you create an abstract method, you provide the
keyword abstract and the intended method type, name, and
argument
When you create a subclass that inherits an abstract method
from a parent, you must use the override keyword
11/21/2025 ANDARGACHEW A. 100
The abstract modifier indicates that the thing
being modified has a missing or incomplete
implementation.
The abstract modifier can be used with classes,
methods, properties, indexers, and events.
Use the abstract modifier in a class declaration
to indicate that a class is intended only to be a
base class of other classes.
Members marked as abstract, or included in an
abstract class, must be implemented by classes that
derive from the abstract class.
11/21/2025 ANDARGACHEW A. 101
Abstract classes have the following features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and
accessors.
It is not possible to modify an abstract class with
the sealed modifier because the two modifiers have
opposite meanings.
The sealed modifier prevents a class from being inherited
and the abstract modifier requires a class to be inherited.
A non-abstract class derived from an abstract class
must include actual implementations of all inherited
abstract methods and accessors.
11/21/2025 ANDARGACHEW A. 102
An abstract method is implicitly a virtual method.
Abstract method declarations are only permitted in
abstract classes.
Because an abstract method declaration provides no
actual implementation, there is no method body; the
method declaration simply ends with a semicolon and
there are no curly braces ({ }) following the signature.

11/21/2025 ANDARGACHEW A. 103


OUTPUT
Rectangle class area :
Area: 70

11/21/2025 ANDARGACHEW A. 104


INTERFACE
An interface is a purely logical construct that
describes functionality without specifying
implementation
An interface in C# contains only the declaration of
the methods, properties, and events, but not the
implementation
An interface generally defines set of methods
that will be implemented by the class
But interface doesn’t implement any method itself
It is left to the class that implements the interface by
11/21/2025 ANDARGACHEW A. 105
Declaring Interface
You define an interface by using the interface
keyword
It is similar to class declaration.
Interface statements are public by default.
Following is an example of an interface
declaration
interface Iaddition
{
int add(int x, int y);
11/21/2025 ANDARGACHEW A. 106
 Any class implementing Compute will be able
to implement both these methods. INTERFACES
CAN EXTEND ONLY INTERFACES, THEY CAN’T
EXTEND CLASSES.
Implementing Interfaces
An Interface can be implemented as follows:

class classname : Interfacename {


body of classname
}
11/21/2025 ANDARGACHEW A. 107
A class can derive from a single class and
implement as many interfaces required:
class classname: superclass,
interface1,interface 2,…
{
body of class name
}
Just as a class can implement multiple interfaces,
one single interface can be implemented by multiple
classes.
11/21/2025 ANDARGACHEW A. 108
Limitations of interface
Interfaces cannot have data members.
They cannot define constructors, destructors .
No member can be declared static.
Difference and similarities between interface and abstract
class
Similarities
Neither can be instantiated
Neither can be sealed
Differences
Interfaces cannot contain any implementation
Interfaces cannot declare non-public members
11/21/2025 ANDARGACHEW A. 109
C# VERSION 8.0 AND GREATER
Important point about Interface in C# version
8.0 and greater
An interface may define a default implementation for
members.
It may also define static members in order to provide
a single implementation for common functionality.
Beginning with C# 11, an interface may define static
abstract or static virtual members to declare that an
implementing type must provide the declared
members.
Typically, static virtual methods declare that an
11/21/2025 ANDARGACHEW A. 110
EXERCISE-13
Define an abstract class Shape with abstract method
CalculateSurface() and fields width and height.
Define two additional classes for a triangle and a
rectangle, which implement CalculateSurface(). This
method has to return the areas of the rectangle
(height*width) and the triangle (height*width/2).
Define a class for a circle with an appropriate
constructor, which initializes the two fields (height and
width) with the same value (the radius) and implement
the abstract method for calculating the area.
Create three different shapes (rectangle, triangle, circle)
and calculate the area of each shape.
11/21/2025 ANDARGACHEW A. 111
EXERCISE-14
Write a C# program to create an abstract class
BankAccount with abstract methods deposit()
and withdraw().
Includes two private attributes account number and
balance in BankAccoutn class.
Create SavingsAccount class that inherits the
BankAccount class and implement the respective
methods to handle deposits and withdrawal.
Includes one private attribute amount in
SavingsAccount class.
Use appropriate constructor and properties for each
class
11/21/2025 ANDARGACHEW A. 112
EXERCISE-15
Write a C# program to create an abstract class
Employee with abstract methods calculateSalary()
and displayInfo(). Add name and base salary
attributes.
Create subclasses Manager and Programmer that extend
the Employee class and implement the respective
methods to calculate salary and display information for
each role.
Include one private attribute bonus in Manager class and
calculate salary by adding base salary with bonus.
Include two private attributes over time hour and hourly
rate in Programmer class and calculate salary by adding
base salary with product of over time hours and hourly
rate.
Use appropriate constructor and properties for each
11/21/2025 ANDARGACHEW A. 113
EXERCISE-16
We have to calculate the percentage of marks
obtained in three subjects (each out of 100) by
student A and in four subjects (each out of 100) by
student B.
Create an abstract class 'Marks' with an abstract method
'getPercentage'.
It is inherited by two other classes 'A' and 'B' each having
a method with the same name which returns the
percentage of the students.
The constructor of student A takes the marks in three
subjects as its parameters and the marks in four subjects
as its parameters for student B.
Create an object for each of the two classes and print the
percentage of marks for both the students.
11/21/2025 ANDARGACHEW A. 114
Questions?

11/21/2025 ANDARGACHEW A. 115


Thank You

11/21/2025 ANDARGACHEW A. 116

You might also like