Chapter-3-WP-with-C#_Object_Oriented_Programming_2.0
Chapter-3-WP-with-C#_Object_Oriented_Programming_2.0
11/12/2024 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/12/2024 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/12/2024 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/12/2024 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/12/2024 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/12/2024 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
11/12/2024 ANDARGACHEW A. 8
❑Inheritance: creating general and specialized version of objects
▪Person
oAttributes:
Name, Id number, Date of Birth, Gender,
Person
registration date, marital status.
▪Student
oAttributes:
department, section, class year.
Student Teacher
▪Teacher
oAttributes:
salary, years of experience, specialized subject.
11/12/2024 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/12/2024 ANDARGACHEW A. 10
11/12/2024 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/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 14
BANK EXAMPLE
class: Account
number: 054
Instance #2
many instances of the account class.
number: 712
balance: $941
11/12/2024 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/12/2024 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/12/2024 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 a single instance
instance of a class. variables
Account
class
variable
count: 3 num: 054 num: 712 num: 036
bal: $19 bal: $240 bal: $941
printCount()
Class
method
11/12/2024 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/12/2024 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/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 23
GRAPHICAL MODEL OF AN OBJECT
Instance balance()
variables
accountNumber()
Methods
11/12/2024 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/12/2024 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/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 29
30
11/12/2024
ANDARGACHEW A.
❑Accessing Objects
▪Referencing the object’s data
objectReference.data
mycircle.radius
▪Invoking the object’s method:
objectReference.method
myCircle.findArea()
11/12/2024 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/12/2024 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/12/2024 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/12/2024 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
ClassName.MethodName( arguments )
eg: Math.Sqrt( 900.0 )
Such functions can access only static variables.
11/12/2024 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/12/2024 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
ClassName.MemberName.
▪A static class remains in memory for the lifetime of the
application domain in which your program resides.
11/12/2024 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/12/2024 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.
▪Access modifiers can be used in constructor declaration to control its access
i.e which other class can call the constructor.
11/12/2024 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/12/2024 ANDARGACHEW A. 40
class Employee //Parameterized Constructor Employee u1= new Employee();
{ public Employee(string a, string b) Employee u2 = new
Employee(“Meron”,”AA”);
private name, location; {
Employee u3 = new Employee(u1) ;
//Default Constructor name = a;
public Employee() location = b;
{ }
public Employee(Employee s)
name = "Alex Len";
{
location = "San Francisco";
name= s.name;
} location= s.location
}
}
11/12/2024 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/12/2024 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/12/2024 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 method.
11/12/2024 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/12/2024 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
11/12/2024 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.
❑Write a test class called TestCircle which demonstrate the
Circle class.
11/12/2024 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
11/12/2024 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
11/12/2024 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
The area of the rectangle is: 42
11/12/2024 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/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 53
EXAMPLE
private int length;
public int Length
{
get
{
return length;
}
set
{
length = value;
}
}
11/12/2024 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#
▪objectOfTheClass.propertyName
▪Getters and setters let you treat the values like public
properties.
11/12/2024 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/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 58
❑Syntax
[access_modifier] [return_type] this [argument_list]
{
get
{
// get block code
}
set
{
// set block code
}
}
11/12/2024 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/12/2024 ANDARGACHEW A. 60
EXAMPLE
11/12/2024 ANDARGACHEW A. 61
11/12/2024 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 exercise, use 28 for February. If the
user inputs an invalid entry, display an appropriate message.
11/12/2024 ANDARGACHEW A. 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 class using C# properties.
11/12/2024 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/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 67
EXAMPLE: EXTENDING EXISTING CLASSES
11/12/2024 ANDARGACHEW A. 68
11/12/2024 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/12/2024 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.
❑Inheritance is transitive; that means a child inherits all the
members of all its ancestors
11/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 73
EXAMPLE: INHERITANCE
11/12/2024 ANDARGACHEW A. 74
Output
11/12/2024 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/12/2024 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 polymorphism.
11/12/2024 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()
{
Console.WriteLine("A::Test()");
}
}
class B : A
{
public override void Test()
{
Console.WriteLine("B::Test()");
}
}
11/12/2024 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/12/2024 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 from it by inheritance. Holiday day;
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/12/2024 ANDARGACHEW A. 80
11/12/2024 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 class.
11/12/2024 ANDARGACHEW A. 82
11/12/2024 ANDARGACHEW A. 83
11/12/2024 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.
11/12/2024 ANDARGACHEW A. 85
11/12/2024 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/12/2024 ANDARGACHEW A. 87
11/12/2024 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/12/2024 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/12/2024 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/12/2024 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/12/2024 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/12/2024 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/12/2024 ANDARGACHEW A. 94
OUTPUT
Printing int: 5
Printing float: 500.263
Printing string:Hello C++
11/12/2024 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/12/2024 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();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
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/12/2024 ANDARGACHEW A. 97
❑Overloadable and Non-Overloadable Operators
▪The following table describes the overload ability of the operators in C# :
No. Operators & Description
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 +=, -=, *=, /=, %= : The assignment operators cannot be overloaded.
6 =, ., ?:, ->, new, is, sizeof, typeof: These operators cannot be overloaded.
11/12/2024 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/12/2024 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