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

Ch3 Object-Oriented Programming in C#..

The document discusses object-oriented programming concepts in C#, including methods, classes, objects, constructors, destructors, properties, inheritance, polymorphism, and access modifiers. It provides examples to explain each concept.

Uploaded by

Elias Khoury
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Ch3 Object-Oriented Programming in C#..

The document discusses object-oriented programming concepts in C#, including methods, classes, objects, constructors, destructors, properties, inheritance, polymorphism, and access modifiers. It provides examples to explain each concept.

Uploaded by

Elias Khoury
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

I3332

3 year Info
rd

Object-Oriented Programming in C#

1
Plan
 Introduction
 Methods
 Classes/ Objects
 Constructors and destructors
 Properties
 Inheriting and extending classes
 Method overriding and polymorphism
 Access modifiers
 Encapsulation principles
 Abstract classes and interfaces

2
Introduction
 OOP stands for Object-Oriented Programming.

 Object-oriented programming has several advantages over procedural


programming:
1. OOP is faster and easier to execute
2. OOP provides a clear structure for the programs
3. OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
4. OOP makes it possible to create full reusable applications with less code and
shorter development time

3
Methods (1/6)
 A method is a block of code which only runs when it is called.
 To create a method with no return value: static void
Methodname().
 Example:
class Program
{
static void MyMethod()
{
// code to be executed
}
}
4
Methods (2/6)
 To call a method: Methodname().
 Example:
static void MyMethod()
{
Console.WriteLine(“Hello World!");
}
static void Main(string[] args)
{
MyMethod();
}
// Outputs “Hello World!"
5
Methods (3/6)
 To pass parameters: Methodname(type parameter name).
 Example:
static void Username(string fstname)
{
Console.WriteLine(fstname + " Refen");
}

static void Main(string[] args)


{
Username("Liam");
}
6
// Liam Refen
Methods (4/6)
 Example:
static void Userage(string fstname, int age)
{
Console.WriteLine(fstname + " is " + age);
}

static void Main(string[] args)


{
Userage("Liam“, 5);
}
// Liam is 5
7
Methods (5/6)
 By using the equals sign (=), a default parameter can be used.
 Example:
static void Country(string country = "Norway")
{
Console.WriteLine(country);
}

static void Main(string[] args)


{
Country("Sweden");
Country();
}
// Sweden 8
// Norway
Methods (6/6)
 To create a method with return value: static type Methodname().
 Example:
static int summethod(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
int z = summethod(6, 3)
Console.WriteLine(z);
}
9
// Outputs 9 (6 + 3)
Classes/ Objects (1/4)
 Class is the blueprint for the object and object is an instance of a
class.
 Example:
the prototype of a house which contains all the details about the
floors, doors, windows, etc. We can build a house based on these
descriptions: prototype= class and house= object.

 To create a class, use the class keyword:


class Car
{
string color = “Blue";
}
10
Classes/ Objects (2/4)
 To create an object: ClassName obj = new ClassName();
 Example:
class Car
{
string color = "red";

static void Main(string[] args)


{
Car Obj = new Car();
Console.WriteLine(Obj.color);
}
}
N.B: the dot syntax (.) is used to access variables/fields inside 11
a class.
Classes/ Objects (3/4)
 Example:
class Car
{
string color; // field
int maxSpeed; // field
static void Main(string[] args)
{
Car Obj1 = new Car();
Obj1.color = "red";
Obj1.maxSpeed = 200;
Console.WriteLine(Obj1.color);
Console.WriteLine(Obj1.maxSpeed);
}
12
}
Classes/ Objects (4/4)
 Example:
class Car
{
string color;// field
public void fullspeed() // method declared as public
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
Car Obj1 = new Car();
myObj.fullspeed(); // Call the method
}
13
}
Constructors and destructors (1/6)
 A constructor is a special method used to initialize object when it is created.

 while creating Constructors:


 It should be the same name of class.
 It never returns value.
 A class may have several constructors.
 A constructors may initialize with our without argument.

14
Constructors and destructors (2/6)
 Example:
class Hello
{
//Constructors
public Hello()
{
}
//Parameterized Constructor
public Hello(int num)
{
}
public Hello(string msg)
{
} 15
}
Constructors and destructors (3/6)
 Destructors are used to removing all the instance of classes and releasing
resources. It works like a garbage collector.
 while creating Destructors:
 Destructor is used followed by tilde (~) Symbol.
 A class can only have one destructor.
 It cannot be called. It is invoked automatically.
 It does not have parameters.
 Example:
class Hello
{
~Hello() // destructor
{
// cleanup statements...
} 16
}
Constructors and destructors (4/6)
 Example: create a class that requires a temperature value in centigrade and in then
use that value in entire class:
//Constructor Creation
public CalculateHeat(int val)
{
temp = Convert.ToInt32(val);
}

public CalculateHeat(string Message)


{
Console.WriteLine(Message.ToString());
}

17
Constructors and destructors (5/6)
// Method creation that converts centigrade to Fahrenheit
public void calculate()
{
decimal fahrenheit = Convert.ToDecimal(temp * 1.8 + 32);
Console.WriteLine("{0} degree centigrade into fahrenheit = {1}", temp,
fahrenheit);
}

//Destructor Initialization, It will clean memory at the end.


~CalculateHeat()
{
Console.WriteLine("Destructor Initializes, Cleanup Process Complete");
Console.ReadLine();
} 18
Constructors and destructors (6/6)
//Object initializing
public static void Main(String[] args)
{
CalculateHeat cl = new CalculateHeat(36);
cl.calculate();

CalculateHeat c2 = new CalculateHeat("I am second constructor");


}

Output:
36 degree centigrade into fahrenheit = 96.8
I am second constructor
Destructor Initializes, Cleanup Process Complete
19
Properties (1/3)
 A property is like a combination of a variable and a method, and it has two
methods: a get and a set method:
 The get method returns the value of the variable.
 The set method assigns a value to the variable.
 Example:
class Person
{
private string name; // field

public string Name // property


{
get { return name; } // get method
set { name = value; } // set method
}
} 20
Properties (2/3)
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
//Output
Liam

21
Properties (3/3)
 C# also provides a way to use automatic properties, only write get; and set; inside the property.
 Example:
class Person
{
public string Name // property
{
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name); //Output Liam
} 22
}
Inheriting and extending classes (1/4)
 In C#, it is possible to inherit fields and methods from one class to another. The "inheritance concept“ is grouped
into two categories:
 Derived Class (child) - the class that inherits from another class
 Base Class (parent) - the class being inherited from
 To inherit from a class, use the : symbol.
 Example:
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void Vehicleprob() // Vehicle method
{
Console.WriteLine(“Check Engine!");
}
}
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
23
}
Inheriting and extending classes (2/4)
 Example:
class Program
{
static void Main(string[] args)
{
Car myCar = new Car(); // Create a myCar object
// Call the Vehicleprob() method (From the Vehicle class) on the myCar object
myCar.Vehicleprob();
// Display the value of the brand field (from the Vehicle class) and the value
of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
24
Inheriting and extending classes (3/4)
 A C# extension method allows developers to extend the functionality of an existing class
without creating a new one. In that case, the "this" modifier is applied to the first
parameter.
 Example:
public class Class1
{
public string Display()
{
return ("I m in Display");
}

public string Print()


{
return ("I m in Print");
} 25
}
Inheriting and extending classes (4/4)
public static class XX
{
public static void NewMethod(this Class1 ob)
{
Console.WriteLine("Hello I m extended method");
}
}
class Program
{
static void Main(string[] args)
{
Class1 ob = new Class1();
ob.Display();// I m in Display
ob.Print();// I m in Print
ob.NewMethod();// Hello I m extended method
} 26
}
Method overriding and polymorphism (1/6)
 Polymorphism is one of the fundamental concept of Object Oriented Programming. It occurs when
we have many classes that are related to each other by inheritance. Used to avoid method overriding.
 Example:
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
} 27
}
Method overriding and polymorphism (2/6)
 Example:
public class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}
public class Triangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a triangle");
}
28
}
Method overriding and polymorphism (3/6)
 Example:
public static void Main()
{
Shape shape1 = new Shape();
Shape shape2 = new Circle();
Shape shape3 = new Rectangle();
Shape shape4 = new Triangle();

shape1.Draw(); // Outputs "Drawing a shape"


shape2.Draw(); // Outputs "Drawing a circle"
shape3.Draw(); // Outputs "Drawing a rectangle"
shape4.Draw(); // Outputs "Drawing a triangle"
}
29
Method overriding and polymorphism (4/6)
 In there are a few rules to follow when using polymorphism:
1. A class can only inherit from a single base class.
2. A method marked as virtual in the base class can be overridden in a derived class using the
override keyword.
3. If a derived class wants to call the implementation of a virtual method from the base class, it
can use the base keyword.
4. If a derived class wants to prevent a virtual method from being overridden in further derived
classes, it can use the sealed keyword.
5. If a derived class wants to provide its own implementation of a virtual method, but also wants
to call the implementation from the base class, it can use the base keyword in the
implementation.

30
Method overriding and polymorphism (5/6)
 Example:
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
public class Circle : Shape
{
public override void Draw()
{
// Call the implementation in the base class
base.Draw();
Console.WriteLine("Drawing a circle");
} 31
}
Method overriding and polymorphism (6/6)
 Example:
public class Rectangle : Shape
{
public sealed override void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}
public class Triangle : Rectangle
{
// This will cause a compile-error because the Draw method is sealed in the Rectangle class
public override void Draw()
{
Console.WriteLine("Drawing a triangle");
} 32
}
Access modifiers
 By now, we are quite familiar with the public keyword which is used to set the
access level/visibility for classes, fields, methods and properties:
public int number;

 C# has the following access modifiers:

Modifier Description
public The code is accessible for all classes
private The code is only accessible within
the same class
protected The code is accessible within the
same class, or in a class that is
inherited from that class.
internal The code is only accessible
within its own assembly, but not from
another assembly.
33
Encapsulation principles
 The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:
1. Declare fields/variables as private
2. Provide public get and set methods, through properties, to access and update the value of a private field.
 Example:
public class BankAccount
{
private decimal balance;

public decimal Balance


{
get { return balance; }
set { balance = value; }
}
}

// Can access balance through the Balance property


BankAccount account = new BankAccount();
account.Balance = 100;
Console.WriteLine(account.Balance); 34
Abstract classes and interfaces (1/4)
 Data abstraction is the process of hiding certain details and showing only essential information to the user. It can
be achieved with either abstract classes or interfaces.
 The abstract keyword is used for classes and methods:
1. Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).
2. 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).
 An abstract class can have both abstract and regular methods:
abstract class baseclass
{
public int num = 5;
public abstract void sum();
}
class childclass : baseclass
{
public override void sum()
{
Console.WriteLine("Total Sum : " + num * num);
35
}
Abstract classes and interfaces (2/4)
namespace Abstract_Method
{
class Program
{
static void Main(string[] args)
{
childclass ch = new childclass();
ch.sum();
}
}
}

//Output
Total Sum : 25
36
Abstract classes and interfaces (3/4)
 Another way to achieve abstraction in C#, is with interfaces.

 An interface is a completely "abstract class", which can only


contain abstract methods and properties (with empty bodies):
interface MyInterface
{
void MyMethod();
string MyProperty { get; set; }
}

37
Abstract classes and interfaces (4/4)
 To implement an interface in C#, you use the : symbol, followed by the name of
the interface. The syntax for implementing an interface is as follows:
class MyClass : MyInterface
{
public void MyMethod()
{
// implementation of MyMethod()
}
public string MyProperty
{
get { return "MyValue"; }
set { }
}
38
}
I3332
3 year Info
rd

Object-Oriented Programming in C#

39

You might also like