You are on page 1of 62

University of Computer Studies

Chapter(5)
OOP Concepts

1
Contents

 Class and Object

 Abstraction

 Inheritance

 Interfaces

 Polymorphism

2
Class and Object

 What is Class and Object?

 Class Syntax

 Property

 Constructor

 Destructor

3
use the keyword new

Class and Object


Class
 A class packages data and related behavior.

Encapsulation
 It is implemented by using access specifiers.
 An access specifier defines the scope and visibility of a class member.
 C# supports the following access specifiers: public, private, protected, internal, protected internal.

Object
 An object is created from a class.
 “ new” keyword can be used to create an object.
 use the dot syntax “ . ” to access variables/fields inside a class.

4
Class Syntax
Syntax

<<attributes>> <<accessibility>> <<abstract | sealed | static >> <<partial>>


class name <<inheritance>>
{
Statements….
}

Attributes
 It refines the definition of a class to give more information to the compiler and the runtime system.

5
Class Syntax
Accessibility
Table 1
Keyword Allowed In Meaning
public namespace the class is visible to all code inside or outside of the
structure class’s assembly

class
internal namespace the class is visible only to code inside the class’s assembly
structure
class
private structure the class is visible only to code inside the containing
class namespace, structure, or class
protected structure the class is visible only to code inside the containing
class structure or class or in a class derived from the containing
class
protected structure combines protected and internal
internal class 6
Class Syntax

 Default access specifier for a class type is internal.

 Default access for the members is private.

 If a class is declared directly within a namespace, its accessibility clause must be either public or internal.

 If a class is declared inside a structure, its accessibility clause can be public, private or internal.

 If a class is declared within a class, the clause can take the values protected and protected internal.

7
Class Syntax
abstract

 If a class’s declaration includes the abstract keyword, instances of this class cannot be created.

 Another class is derived from this abstract class.

 Instances of the derived class can be created. abstract class Shape


{
protected string color;

public abstract void CalculateArea( );


public void Show( )
{
Console.WriteLine(color);

}
8
Class Syntax

sealed sealed class SealedExample


 If a class’s declaration includes the sealed keyword, {
public int Add(int x, int y)
other classes cannot be derived from it. {
return x + y;
}
}

class Program
{
static void Main(string[] args)
{
SealedExample s = new SealedExample( );
int total = s.Add(4, 5);
Console.WriteLine("Total = " + total.ToString());

}
} 9
Class Syntax
sealed class Animal {

class Dog : Animal {

class Program {
static void Main (string [] args) {

Dog d1 = new Dog();


Console.ReadLine();
}
}

error : 'Dog': cannot derive from sealed type 'Animal'


10
Class Syntax

static

 If a class’s declaration includes the static keyword, other classes cannot be derived from it and its instances
cannot be created.

 Members of static class are invoked by using the class’s name instead of an instance.

 All members (attributes and methods) of a static class must also be declared static.

11
Class Syntax

public static class Calculator class Program


{ {
private static int resultStorage = 0; static void Main(string[] args)
{
public static string Type = "Arithmetic"; var result = Calculator.Sum(10, 25);

public static int Sum(int num1, int num2) Calculator . Store(result);


{
return num1 + num2; Calculator . Type = "Scientific";
}
}
public static void Store(int result) }
{
resultStorage = result;
}
}

12
Class Syntax

partial
partial class Person
 This keyword tells C# that the current declaration defines only
{
part of the class.
public string FirstName, LastName;
 A class can be broken into any number of pieces.
}
 All of them must include the partial keyword.
 At compile time, C# finds the pieces and combines them to define partial class Person
the class. {
public string Street, City, State, Zip;
}

13
Class Syntax

class name

 The name of the class must be a valid C# identifier name.

Inheritance

 To inherit from a class, use the “ : ” symbol

 Base Class (parent) - the class whose members are inherited

 Derived Class (child) - the class which inherits the members of another class

14
Property

 The property’s get and set accessors allow the program to get and set the property’s value.

To create an auto-implemented property

class Person
{
public string name {get; set; }
}

Person p = new Person( );


p.name = “Su Su”;
Console.WriteLine(p.name);

15
Property
To create get/set properties

class Person
{
private string name;

public string PersonName


{
get
{ return name; }

set
{ name=value; }
}
}

Person p = new Person( );


p.PersonName = “Su Su”;
Console.WriteLine(p.PersonName);
16
Property
To create get/set properties
class Person
{ private string FirstName, LastName;
public string PersonName
{
get
{ return FirstName + “ ” + LastName;}

set
{ FirstName = value.Split(‘ ’)[0];
LastName = value.Split(‘ ’)[1];
}

}
}

Person p = new Person( );


p.PersonName = “Su Su”;
17
Console.WriteLine(p.PersonName);
Constructor

 It is a special method.

 It has exactly the same name as that of the class and it does not have any return type.

 It is executed whenever new objects of that class are created.

 It helps to assign initial value to an object at the time of its creation.

 A default constructor does not have any parameter.

 A constructor with parameters is called parameterized constructor.

 “this” keyword is used to automatically invoke another constructor.

 “base” keyword is used to invoke a constructor in the parent class.

18
Constructor

Example

1. 2.
class Person class Person
{ private string name; } { private string name;
public Person( string st)
Person p = new Person( ) ; { name = st; }
}
Person p = new Person( “Yu Yu”);

19
Constructor

3. 4.
class Person class Person
{ private string name; { private string name;
public Person( ) public Person( string st= “unknown” )
{ name = “unknown”; } { name = st; }
public Person( string st) }
{ name = st; }
} Person p1 = new Person( ) ;
Person p2= new Person(“Pa Pa”) ;
Person p1 = new Person( ) ;
Person p2 = new Person(“Chaw Chaw”) ;

20
Constructor

5. 6.
class Person class Student : Person
{ private string name; { private string rno;
public Person( string st) public Student(string stdname, string stdrno)
{ name = st; } :base(stdname)
public Person( ) { rno = stdrno; }
: this(“unknown”)
{ } public Student(string stdname )
} : this(stdname, “unknown”)
Person p1 = new Person( ) ; { }
Person p2= new Person(“Khin Khin”) ; }
Student p1 = new Student(“Thaw Thaw”, “3CS-1” );
Student p2= new Student(“Khin Khin”); 21
Destructor

 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.

22
Abstraction

 What is Abstraction?

 Abstract Class and Method Syntax

 Abstract Class and Method Example

23
Abstraction

 Data abstraction is the process of hiding certain details and showing only essential information to the user.

 Abstraction can be achieved with either abstract classes or interfaces.

 Abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from
another class).

 Abstract method can only be used in an abstract class, and it does not have a body.

 The body is provided by the derived class (inherited from).

 The abstract keyword is used for classes and methods.

 An abstract class can have both abstract and regular methods:

 To access the abstract class, it must be inherited from another class.

24
Abstract Class and Method Syntax

Abstract Class Syntax Abstract Method Syntax

class
abstract class Geometric name
public abstract void geek( );
{
abstract Method
keyword name
} abstract
keyword
keyword

25
Abstract Class and Method Example
abstract class Shape class Rectangle : Shape class Program
{ { {
protected string color; double width; static void Main(string[] args)
double height; {
public void ShowColor()
{ public Rectangle(string c, double w, double h) Rectangle r = new Rectangle("Orange",
Console.WriteLine("Color: " + color); { 20.5, 30.3);
} base.color = c; r.CalculateArea();
width = w; r.ShowColor();
public abstract void CalculateArea(); height = h;
Console.ReadLine();
} } }
}
public override void CalculateArea()
{
double area = width * height;
Console.WriteLine("Area = " + area);
}
}

26
Inheritance

What is Inheritance?

Base Class and Derived Class

Advantages of Inheritance

Types of Inheritance

Inheritance Example

27
Inheritance

 One of the most important concepts in OOP is inheritance.

 It is a concept in which parent classes and child classes are defined.

 The class which inherits the members of another class is called derived class.

 The class whose members are inherited is called base class.

 The child classes inherit attributes and behaviors of the parent classes.

 Attributes and behaviors which is defined in base class can be reused, extended or modified.

 C# does not support multiple inheritance.

28
Base Class and Derived Class

 Base Class (parent) - the class whose members are inherited

 Derived Class (child) - the class which inherits the members of another class

 The derived class is the specialized class for the base class

 The based class is the generalized class for the derived class

 To inherit from a class, use the “ : ” symbol

29
Base Class and Derived Class
Syntax:

class Employee Base Class


{ “Employee” class is a generalization of
public string name; “FullTimeEmployee” class.
public double salary;

}
Derived Class Base Class

class FullTimeEmployee : Empolyee


{ “FullTimeEmployee” class is a specialization
of “Employee” class.
public double bonus;
}
30
Advantages of Inheritance

 It provides code reusability.


 It reduces code redundancy.
 Reduces source code size and improves code readability.

31
Types of Inheritance

 Simple or Single Inheritance


 Multilevel Inheritance
 Multiple Inheritance (achievable using the
Interface)
 Hierarchical Inheritance
 Hybrid Inheritance

32
Single and Multi-level Inheritance

Simple Or Single Inheritance: a process in which the Multilevel inheritance: a derived class will inherit a
derived class inherits properties and behavior from a base class and as well as the derived class also act as the
single base class. base class to other class.

Single Inheritance Multi-Level Inheritance

Person Base Class Person Base Class

Derived class of Person class


Employee Base class of FullTimeEmployee
Employee Derived Class

Person class is generalization of Employee class FullTimeEmployee Derived class of Employee class
Employee class is specialization of Person class
33
Multiple and Hierarchical Inheritance

Multiple Inheritance: The derived class derives from two Hierarchical inheritance: More than one class is inherited
or more base classes. The derived class uses the combined from a single parent or base class.
features of the multiple base classes.
Figure Multiple and Hierarchical

Multiple Inheritance Hierarchical Inheritance

Person Employee Employee

Teacher
FullTimeEmployee PartTimeEmployee

34
Hybrid Inheritance

 Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.
 In this type, more than one type of inheritance are used to derive a new sub class.

GrandFather Single
Inheritance

Father
Hierarchical
Inheritance

Son Daughter Hybrid


Inheritance
35
Inheritance Example

class Animal { class Program {

public string name; static void Main(string[] args) {

public void display() {


Console.WriteLine("I am an animal"); Dog d = new Dog();
}
} d.name = “Puppy";
d.display();
class Dog : Animal { d.getName();

public void getName() { Console.ReadLine();


Console.WriteLine("My name is " + name); }
}
} }

36
Interface

 What is Interface?

 Interface Syntax

 Interface Implementation

 Implementing Multiple Interfaces

 Implementing Interface Implicitly

 Implementing Interface Explicitly

37
Interface

Base Class 1 Base Class 2

Derived Class

 C# does not support multiple inheritance.


 Multiple inheritance is possible with the help of interfaces but not with classes.

38
Interface
 Interfaces define what operations a class can perform.

 It defined properties, methods and events which are the members of the interface.

 It is like abstract class because all the methods which are declared inside the interface are abstract methods.

 It cannot have method body and cannot be instantiated.

 It is the responsibility of the deriving class to define the members.

 Interface can only contain declarations but not implementations.


 Interface cannot contain data members(fields), auto-implemented properties.
 Access modifiers cannot be applied to interface members.
 All the members are public by default and abstract.
 No member can be declared static.
39
Interface Syntax
Using “interface” keyword

interface <interface_name > Interface names should begin


with a capital “I”
{
// declare Events
// declare indexers interface IPolygon
{ IPolygon
// declare methods
<< interface>>
// declare properties void calculateArea( );
calculateArea( )
}
}

No access specifiers No method body

40
Interface Implementation

 A class or a struct can implement one or more interfaces using colon ( : ).

 An interface can inherit one or more interfaces.

 Two ways to implement interface

 Implicit Implementation

 Explicit Implementation

41
Implementing Interface Implicitly

 Implicit implementations don't include the name of the interface being implemented before the member name,

so the compiler infers this.

 With implicit interface implementations, the members of the interface are public in the class.

 The members will be accessible when the object is cast as the concrete type.

 Interface members must be implemented with the public modifier; otherwise, the compiler will give

compile-time errors.

42
Implementing Interface Implicitly

interface IPolygon class Rectangle : IPolygon


{ {

void calculateArea(dobuble l, double b ); public void calculateArea(double l , double b)


{
} int area = l * b;
Console.WriteLine("Area of Rectangle: " + area);
}

43
Implementing Interface Explicitly

 To implement explicitly by prefixing interface name with all the members of an interface.

 Do not use “public” modifier with an explicit implementation. (compile time error).

 You cannot declare methods as virtual.

 With explicit implementations, the interface members in the class are not declared as public members and cannot be
directly accessed using an instance of the class, but a cast to the interface allows accessing the members.

 Explicit implementation is useful when class is implementing multiple interfaces.

 It is more readable and eliminates the confusion.

 It is also useful if interfaces have the same method name coincidently.

44
Implementing Interface Explicitly

class FileInfo : IFile , IBinaryFile


interface IFile {
{ void IFile.ReadFile()
{
void ReadFile();
Console.WriteLine("Reading Text File");
} }

interface IBinaryFile void IBinaryFile.OpenBinaryFile()


{ {
void OpenBinaryFile(); Console.WriteLine("Opening Binary File");
void ReadFile(); }
}
void IBinaryFile.ReadFile()
{
Console.WriteLine("Reading Binary File");
}
} 45
Implementing Multiple Interfaces

 A class can implement one or more interfaces


interface IPolygon
 An interface can extend zero or more interfaces {
void calculateArea(int a, int b);
 A class can be more accessible than its base interfaces }

 An interface cannot be more accessible than its base interfaces interface IColor
{
 A class must implement all inherited interface methods void getColor();
}

IPolygon IColor class Rectangle : IPolygon, IColor


<< interface >> << interface >> {…..
}

Rectangle
<< concrete >>
46
Example 1(Implicit Implementation)
class Program
interface IDrawable class Rectangle : IDrawable {
{ { static void Main(string[] args)
void Draw(); public void Draw() {
{
} Console.WriteLine("drawing
Rectangle"); Rectangle r1 = new Rectangle();
} r1.Draw();

} IDrawable r2 =new Rectangle();

r2.Draw();

Console.ReadLine();

}
} 47
Example 2(Explicit Implementation)
interface ITransaction class Transaction : ITransaction
{ void ITransaction . showTransaction()
void showTransaction(); { {
double getAmount(); private string tCode; Console.WriteLine("Transactio Code: " + tCode);
private string date; Console.WriteLine("Transaction Date: " + date);
} private double amount; Console.WriteLine("Amount : " + amount);
}
public Transaction()
{ double ITransaction . getAmount()
tCode = ""; {
date = ""; return amount;
amount = 0.0;
} }

public Transaction(string tCode, string date, }


double amount)
{
this.tCode = tCode;
this.date = date;
this.amount = amount;
}

48
Example 2(Explicit Implementation)

class Program
{
static void Main(string[] args)
{

ITransaction t1 = new Transaction( );

ITransaction t2 = new Transaction("00002", "1/12/2020", 20000000);

t1.showTransaction();
t2.showTransaction();

Console.ReadLine();
}
}

49
Polymorphism

What is Polymorphism

Types of Polymorphism

Static Polymorphism

Dynamic Polymorphism

50
Polymorphism

 Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by

inheritance.

 Inheritance lets us inherit fields and methods from another class.

 Polymorphism uses those methods to perform different tasks.

 This allows us to perform a single action in different ways.

51
Types of Polymorphism

Polymorphism

Compile time Polymorphism Run time Polymorphism


(Static or Early Binding) (Dynamic or Late Binding)

Method Operator Method


Overloading Overloading Overriding

52
Static Polymorphism

 Decision about which method will be called is made at the compile time.

 It is also called static or early binding.

 C# provides two techniques to implement static polymorphism

 Function overloading

 Operator overloading

Function Overloading

 Multiple definitions for the same function name in the same scope

 The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.

 You cannot overload function declarations that differ only by return type.

53
Static Polymorphism
Operator Overloading
 Overloading means the same function name, but the different signatures.
 In operator overloading, we overload the operator instead of the actual method.
 Operators can be considered as function for the compiler.
 Only a predefined set of operators can be overloaded.
 Use operator keyword to implement operator overloading .
 The return type of operator overload can never be void.
 It must include both public and static modifiers.

Operator Overloading Syntax

public static classname operator + (parameters)


{
// Code to be executed
}
54
Static Polymorphism
Operators Description

+, -, !, ~, ++, --, true, false These unary operators take one operand and can be overloaded.

+, -, *, /, % These binary operators take two operands and can be overloaded.

+, -, *, /, % These binary operators take two operands and can be overloaded.

==, !=, <, >, <=, >= The comparison operators can be overloaded.

&&, || The conditional logical operators can’t be overloaded directly but these
can be evaluated by using the & and | which can be overloaded.
+=, -=, *=, /==, %== The compound assignment operators can’t be overloaded.

^, =, ? :, ->, is, new, sizeof, typeof, These operators can’t be overloaded.


nameof, default
55
Dynamic Polymorphism

 It is run-time or late binding polymorphism because of the decision about which method is to be called is

made at run time.

 In dynamic polymorphism, we override the base class method in derived class using inheritance.

 This can be achieved using override and virtual keywords.

 Same method name and signature (same number of parameters and type but with different definitions) too in

parent and child class.

56
Differences between Method Overloading and
Method Overriding
Method Overloading Method Overriding
Method overloading means methods with the same name but Method overriding means methods with the same name and
different signature (number and type of parameters) in the same signature but in a different scope.
same scope.
It is performed within a class, and not require inheritance. It is performed in two classes with inheritance relationships.
It always needs inheritance.

The return type may be the same or different. The return type must be the same.

It is an example of compile-time polymorphism. It is an example of run-time polymorphism.

Static methods can be overloaded. Static methods can’t be overridden.

57
Method Overloading Example

class Calculate
class Program
{
{
public void Sum(int a, int b)
static void Main(string[] args)
{
{
Console.WriteLine("Sum of two numbers: " + (a + b));
} Calculate c = new Calculate();
public void Sum(int a, int b,int c)
c.Sum(20.4, 3.5);
{
c.Sum(20, 40);
Console.WriteLine("Sum of three numbers: " + (a + b+c));
c.Sum(20, 40, 50);
}
Console.ReadLine();
public void Sum(double x, double y)
}
{
}
Console.WriteLine("Sum of two numbers: " + (x+y));
}
}

58
Operator Overloading Example
class Rectangle class Program
{ {
static void Main(string[] args)
public int width; {
public int height; Rectangle r1 = new Rectangle();
r1.width = 30;
public static Rectangle operator +(Rectangle rr1, Rectangle rr2) r1.height = 25;
{
Rectangle rr = new Rectangle(); Rectangle r2 = new Rectangle();
rr.width = rr1.width + rr2.width; r2.width = 15;
rr.height = rr1.height + rr2.height; r2.height = 10;

return rr; Rectangle r3 = r1 + r2 ;

Console.WriteLine("Two Rectangles Addition : Width = " +


} r3.width + ", Height = " + r3.height);

Console.ReadLine();

}
}
59
Dynamic Polymorphism Example
class Person class Student: Person class Employee: Person
{ { {
public string rollno; public string ID;
public string name;
public virtual void Show() public override void Show() public override void Show() {
{ { Console.WriteLine("Name : " + name);
Console.WriteLine("Name : " + Console.WriteLine("Name : " + name); Console.WriteLine("ID: " + ID);
name); Console.WriteLine("RollNo : " + rollno);
} }
} }
}
}

60
Dynamic Polymorphism Example

class Program
{
static void Main(string[] args)
{

Person p = new Person();


p.name = "Su Su";

Employee e = new Employee();


e.name = "Kyaw Kyaw";
e.ID="E001";

Student s = new Student();


s.name = "Ma Ma";
s.rollno = "3CS-3";

p.Show();
e.Show();
s.Show();
Console.ReadLine();
}
} 61
Thank You

62

You might also like