0% found this document useful (0 votes)
16 views

6.OOP Concepts (Updated)

Uploaded by

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

6.OOP Concepts (Updated)

Uploaded by

jaycoab2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 114

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
Class and Object

4
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.
5
new

Class and Object

•Why do we need real-world objects in a Project?

•We need real-world objects in a project because real-world objects are part of our business.
As we are developing applications (software) for automating the business, we must have to
create the business-related real-world objects in the project.

•For example, to automate the Bank business we must create real-world objects like
Customers, Managers, Clerks, Office Assistants, Marketing Executives, Computers, Printers,
Chairs, tables, etc

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

7
Class Syntax
Accessibility
Table 1 Keyword Allowed In Meaning
public namespace the class is visible to all code inside or outside of the
class’s assembly
structure
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 8
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.

8
Abstract Class
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 13
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.

14
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;
}

16
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

17
Quiz
Quiz
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);

20
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);
21
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”;
Console.WriteLine(p.PersonName); 17
Property of Console Class
//Program to show the use of Console Class Properties and Beep Method
using System;
namespace MyFirstProject
{
internal class Program
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.Title = "Understanding Console Class";
Console.WriteLine("BackgroundColor: Blue");
Console.WriteLine("ForegroundColor: White");
Console.WriteLine("Title: Understanding Console Class");
//It will make Beep Sound
Console.Beep();
Console.ReadKey();
}
}
}
Property Example
class Program
using System; {
namespace EncapsulationDemo public static void Main()
{ {
public class Bank try
{ {
private double _Amount; Bank bank = new Bank();
public double Amount
//We cannot access the _Amount Variable directly
{
get //bank._Amount = 50; //Compile Time Error
{ //Console.WriteLine(bank._Amount); //Compile Time Error
return _Amount; //Setting Positive Value using public Amount Property
} bank.Amount= 10;
set //Setting the Value using public Amount Property
{ Console.WriteLine(bank.Amount);
// Validate the value before storing it in the _Amount variable
//Setting Negative Value
if (value < 0)
{ bank.Amount = -150;
throw new Exception("Please Pass a Positive Value"); Console.WriteLine(bank.Amount);
} }
else catch (Exception ex)
{ {
_Amount = value; Console.WriteLine(ex.Message);
}}}}
}
Console.ReadKey();}}}
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.

27
Constructor (Initialized the members used to
create objects)

Without constructors,
we cannot create
objects
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”);

29
Constructor

3. 4.
class Person class Person
{ private string name; { private string name;
public Person( ) public Person( string st= “unknown” )
{ } { name = st;
}

name = “unknown”; public }

Person( string st)


{

name = st;

} Person p1 = new Person( ) ; 30


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(“unkn
{ public Student(string stdname )
own”)
} : 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
Quiz
Destructor

• 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.
• Internally, Destructor called the Finalize method on the base class of object.

22
Destructor Example
Destructor Example
Abstraction

 What is Abstraction?

 Abstract Class and Method Syntax

 Abstract Class and Method Example

23
Class and Object

3
7
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. 38


Abstract Class and Method Syntax

Abstract Class Syntax Abstract Method Syntax

class
abstract class Geometric public abstract void geek( );
{ name

abstract Method
keyword name
} abstract
keyword
keyword

39
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);
}
}

40
Inheritance

 What is Inheritance?

 Base Class and Derived Class

 Advantages of Inheritance

 Types of Inheritance

 Inheritance Example

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

42
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

43
Base Class and Derived Class
Syntax:

class Employee Base Class


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

class FullTimeEmployee : Empolyee


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

 It provides code reusability.


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

45
Types of Inheritance

 Simple or Single Inheritance


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

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

Multiple Inheritance Hierarchical Inheritance


Figure
Multiple and Hierarchical

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(" Dog d = new Dog();
I am an animal");
} d.name = “Puppy";
} d.display();
d.getName();
class Dog : Animal
Console.ReadLine()
{ public void ;
}
getName() {
Console.WriteLine("My
}
name is " + name);
}
} 36
Interface

 What is Interface?

 Interface Syntax

 Interface Implementation

 Implementing Multiple Interfaces

 Implementing Interface Implicitly

 Implementing Interface Explicitly

51
Abstract class Vs Interface
Abstract class Vs Interface
Abstract class Vs Interface
Abstract class Vs Interface
Abstract class Vs Interface
Abstract class Vs Interface
Abstract class Vs Interface
Abstract class Vs Interface
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.

60
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. 61
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

62
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

63
Implicit Vs Explicit Interface Implementation
Why Explicit? When Need Explicit?
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.

66
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);
}

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

68
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 >>
70
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();

}
}
71
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;
}

72
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();
}
}

73
Polymorphism

 What is Polymorphism

 Types of Polymorphism

 Static Polymorphism

 Dynamic Polymorphism

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

75
Types of Polymorphism

Polymorphism

Compile time Polymorphism Run time Polymorphism


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

Method Operator Method


Overloading Overloading Overriding

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

77
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
}
78
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
79
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.

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

81
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));
}
}

82
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Operator Overloading Example
class Rectangle class Program
{ {
static void Main(string[] args)
public int width; {
public int Rectangle r1 = new Rectangle();
height; r1.width = 30;
r1.height = 25;
public static
Rectangle Rectangle r2 = new Rectangle();
operator + r2.width = 15;
(Rectangle rr1, r2.height = 10;
Rectangle rr2)
{ Rectangle r3 = r1 + r2 ;
Rectangle rr = new Rectangle();
rr.width = rr1.width + rr2.width; Console.WriteLine("Two
rr.height = rr1.height + rr2.height; Rectangles Addition : Width = "
+
return rr; r3.width + ", Height
= " + r3.height);

} Console.ReadLine();
91
}
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 : " +
Console.WriteLine("Name : " + Console.WriteLine("Name : " + name); name); Console.WriteLine("ID: " +
name); Console.WriteLine("RollNo : " + rollno); ID);
}
} }
} }
}

92
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
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
62

You might also like