Professional Documents
Culture Documents
6.OOP Concepts
6.OOP Concepts
Chapter(5)
OOP Concepts
1
Contents
Abstraction
Inheritance
Interfaces
Polymorphism
2
Class and Object
Class Syntax
Property
Constructor
Destructor
3
use the keyword 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.
4
Class Syntax
Syntax
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
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.
}
8
Class Syntax
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.
11
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;
}
13
Class Syntax
class name
Inheritance
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.
class Person
{
public string name {get; set; }
}
15
Property
To create get/set properties
class Person
{
private string name;
set
{ name=value; }
}
}
set
{ FirstName = value.Split(‘ ’)[0];
LastName = value.Split(‘ ’)[1];
}
}
}
It is a special method.
It has exactly the same name as that of the class and it does not have any return type.
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.
22
Abstraction
What is Abstraction?
23
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.
24
Abstract Class and 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?
Advantages of Inheritance
Types of Inheritance
Inheritance Example
27
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.
28
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
29
Base Class and Derived Class
Syntax:
}
Derived Class Base Class
31
Types of 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.
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
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
36
Interface
What is Interface?
Interface Syntax
Interface Implementation
37
Interface
Derived Class
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.
40
Interface Implementation
Implicit Implementation
Explicit Implementation
41
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.
42
Implementing Interface Implicitly
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).
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.
44
Implementing Interface Explicitly
An interface cannot be more accessible than its base interfaces interface IColor
{
A class must implement all inherited interface methods void getColor();
}
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();
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;
} }
48
Example 2(Explicit Implementation)
class Program
{
static void Main(string[] args)
{
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.
51
Types of Polymorphism
Polymorphism
52
Static Polymorphism
Decision about which method will be called is made at the compile time.
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.
+, -, !, ~, ++, --, true, false These unary operators take one operand 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.
It is run-time or late binding polymorphism because of the decision about which method is to be called is
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
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.
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;
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)
{
p.Show();
e.Show();
s.Show();
Console.ReadLine();
}
} 61
Thank You
62