6.OOP Concepts (Updated)
6.OOP Concepts (Updated)
Studies
Chapter(5)
OOP
Concepts
1
Contents
Abstraction
Inheritance
Interfaces
Polymorphism
2
Class and Object
Class Syntax
Property
Constructor
Destructor
3
Class and Object
4
new
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
•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
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
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.
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 Program {
static void Main (string [] args) {
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
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
Inheritance
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.
class Person
{
public string name {get; set; }
}
20
Property
To create get/set properties
class Person
{
private string name;
}
}
It is a special method.
It has exactly the same name as that of the class and it does not have any return
type.
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 = st;
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 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?
23
Class and Object
3
7
Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to the
user.
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.
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?
Advantages of Inheritance
Types of Inheritance
Inheritance Example
41
Inheritance
The class which inherits the members of another class is called derived 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.
42
Base Class and Derived Class
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
43
Base Class and Derived Class
Syntax:
45
Types of 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.
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.
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
What is Interface?
Interface Syntax
Interface Implementation
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
Derived Class
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.
62
Interface Implementation
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,
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
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).
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.
68
Implementing Interface Explicitly
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();
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;
} }
72
Example 2(Explicit Implementation)
class Program
{
static void Main(string[] args)
{
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.
75
Types of Polymorphism
Polymorphism
76
Static Polymorphism
Decision about which method will be called is made at the compile time.
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.
+, -, !, ~, ++, --, true, false These unary operators take one operand and can be overloaded.
==, !=, <, >, <=, >= The comparison operators can be overloaded.
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.
Same method name and signature (same number of parameters and type but with different definitions) too in
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.
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)
{
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