0% found this document useful (0 votes)
28 views55 pages

Chapter-5 Object Oriented in Visual C#

Chapter 5 of the document covers Object-Oriented Programming (OOP) concepts in Visual C#, including defining classes, access modifiers, constructors, and various OOP principles such as encapsulation, inheritance, and polymorphism. It explains the structure and behavior of classes, the importance of access modifiers for encapsulation, and how constructors initialize object states. The chapter also discusses methods, properties, and the handling of exceptions in OOP, emphasizing the benefits of modularity, reusability, and maintainability in software development.

Uploaded by

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

Chapter-5 Object Oriented in Visual C#

Chapter 5 of the document covers Object-Oriented Programming (OOP) concepts in Visual C#, including defining classes, access modifiers, constructors, and various OOP principles such as encapsulation, inheritance, and polymorphism. It explains the structure and behavior of classes, the importance of access modifiers for encapsulation, and how constructors initialize object states. The chapter also discusses methods, properties, and the handling of exceptions in OOP, emphasizing the benefits of modularity, reusability, and maintainability in software development.

Uploaded by

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

COURSE TITLE:

WINDOWS PROGRAMMING
Chapter- 5
Object Oriented in visual C#

By Meresa H.(MSc.)

1
Topics:

1. Defining Classes
2. Access Modifiers
3. Constructors
4. Fields, Constants and Properties
5. Static Members
6. Structures
7. Delegates and Events
8. Interfaces
9. Inheritance
10.Polymorphism
2
1. Defining Classes

1. Overviews of OOP
■ Object-Oriented Programming (OOP) is a programming paradigm
based on the concept of "objects," which can contain data (in the form
of fields, often referred to as attributes) and code (in the form of
methods, also called functions).
■ OOP is widely used in software development because it promotes
organization, reusability, and scalability.

Concepts of an Object Program organization 3


1. Defining Classes
1. Overviews of OOP
■ Here are some key concepts:
➢ Classes and Objects:
✓ Classes are a description, data structure, blueprint/Design, or Template for
creating an objects. They define properties and methods that the objects will
have.

➢ Encapsulation:
✓ This hides the internal state of the object and requires all interaction to be
performed through an object's methods.
✓ Combines data and methods into a single unit (the object).
✓ Protects the internal state of the object by restricting direct access to some of its
components.
✓ Example: Private variables in an object are accessed and modified using public
methods (getters and setters).
4
1. Defining Classes
1. Overviews of OOP
➢ Inheritance:
✓ Allows a class (child class) to inherit properties and behaviors from
another class (parent class).
✓ Promotes code reuse and establishes a hierarchical relationship.
✓ Example: A Car class might inherit from a Vehicle class, gaining
attributes like speed and fuel.
➢ Polymorphism:
✓ Allows methods to do different things based on the object it is acting
upon, even if they share the same name.
✓ Enables objects to be treated as instances of their parent class rather
than their actual class.
✓ Allows a single interface to represent different underlying forms
(methods).
✓ Example: A method drive() might behave differently for a Car object and
a Bike object.
5
1. Defining Classes
1. Overviews of OOP
➢ Abstraction:
✓ Simplifies complex systems by modeling
classes appropriate to the problem, and
working at the most relevant level of
inheritance for a particular aspect of the
problem.
✓ Hides implementation details and shows only
the essential features of an object.
✓ Focuses on what an object does rather than
how it does it.
✓ Eg.: A Payment class could have an abstract
method process() that is implemented
differently in CreditCardPayment and
PaypalPayment.

6
1. Defining Classes
■ Benefits of OOP
– Modularity: Code is organized into
self-contained objects, making it easier
to manage.
– Reusability: Objects and classes can
be reused in different parts of the
program or in other programs.
– Scalability: OOP designs are easier to
scale as the system grows.
– Maintainability: Changes can be
made with minimal impact on other
parts of the program

7
1. Defining Classes
■ OOP and .NET
➢ In .NET Framework the object-oriented approach has roots in
the deepest architectural level
➢ All .NET applications are object-oriented
➢ All .NET languages are object-oriented
➢ The class concept from OOP has two realizations:
➢ Classes and structures
➢ There is no multiple inheritance in .NET
➢ Classes can implement several interfaces at the same time

8
1. Classes in OOP
■ Classes model real-world objects and define:
– Attributes (state, properties, fields)
– Behavior (methods, operations)
■ Classes describe the structure of objects
– Objects describe particular instance of a class
■ Properties hold information about the modeled
object relevant to the problem
■ Method implement the operations based on the
object behavior

9
1. Classes in C#
■ Classes in C# can have members:
– Fields, constants, methods, properties, indexers, events,
operators, constructors, destructors, …
– Inner types (inner classes, structures, interfaces, delegates, ...)
■ Members can have access modifiers (scope)
– public, private, protected, internal
■ Members can be
– static (common) or specific for a given object (per instance)

10
1. Classes in C#
■ In this example, we declare a class with ‘MethodDemo’ as a class name

11
Simple Class Definition
public class Cat : Animal Beginning of class definition
{
private string name;
Field Inherited (base) class
public Cat(string name, string owner)
{
this.Name = name; Parametrs
this.Owner = owner;
} Constructor

public string Name Property


{
get { return this.name; }
set { this.name = value; }
}
12
Simple Class Definition (2)
public string Owner
{
get; Automatic Property
set;
}
Method
public void SayMiau()
{
Console.WriteLine("Miauuuuuuu!");
}
}

End of class
definition
13
1. Class Definition and Members
■ Class definition consists of:
– Class declaration
– Inherited class and implemented interfaces
– Fields (static or not)
– Constructors (static or not)
– Properties (static or not)
– Methods (static or not)
– Events, inner types, etc.

14
Fields
■ Fields are data members defined inside a class
– Fields hold the internal object state
– Can be static or per instance
– Can be private / public / protected / …

class Dog
{
private string name;
private string breed; Field
private int age; declarations
protected Color color;
}
Constant Fields
■ Constant fields are of two types:
– Compile-time constants – const
■ Replaced by their value during the compilation
– Runtime constants – readonly
■ Assigned once only at object creation

class Math
{
public const float PI = 3.14159;
public readonly Color = Color.FromRGBA(25, 33, 74, 128);
}
16
Constant Fields – Example
public class Constants
{
public const double PI = 3.1415926535897932385;
public readonly double Size;
public Constants(int size)
{
this.Size = size; // Cannot be further modified!
}
static void Main()
{
Console.WriteLine(Constants.PI);
Constants c = new Constants(5);
Console.WriteLine(c.Size);
c.Size = 10; // Compilation error: readonly field
Console.WriteLine(Constants.Size); // Compilation error: non-static field
}
}
17
2. Access Modifiers
■ Access Modifiers in Object-Oriented Programming (OOP) are keywords
that define the visibility or accessibility of classes, methods, and
attributes.
■ They control where a particular piece of code can be accessed and are
essential for encapsulation.
■ Class members can have access modifiers
– Used to restrict the access from the other classes
– Supports the OOP principle "encapsulation"
■ Class members can be:
– public – accessible from any class
– protected – accessible from the class itself and all its descendants
– private – accessible from the class itself only
– internal (default) – accessible from the current assembly, i.e. the
current Visual Studio project 18
2. Access Modifiers
■ The Common Access Modifiers are:-
– Public:
■ Accessible from anywhere in the program.
■ Methods or attributes marked as public can be used by any other class or object.
– Private:
■ Accessible only within the class where it is defined.
■ Ensures that sensitive data or implementation details are hidden from other
classes.
■ In many languages, private members are not directly accessible by child classes
– Protected:
■ Accessible within the class and its subclasses (child classes).
■ Provides a balance between public and private access.
– Internal:
■ Accessible from the current assembly (used by the default)
19
2. Access Modifiers
The "this" Keyword
■ The keyword this points to the current instance
of the class
■ Example:
class Dog
{
private string name;

public void PrintName()


{
Console.WriteLine(this.name);
// The same like Console.WriteLine(name);
}
}
20
USING CLASSES AND OBJECTS
Dog Meeting – Example
static void Main()
{
Console.Write("Enter first dog's name: ");
string dogName = Console.ReadLine();
Console.Write("Enter first dog's breed: "); // major dog groups: Working,
Herding, Toy, Hound, Sporting, Non-Sporting, and Terrier
string dogBreed = Console.ReadLine();
// Use the Dog constructor to assign name and breed
Dog firstDog = new Dog(dogName, dogBreed);
// Use Dog's parameterless constructor
Dog secondDog = new Dog();
// Use properties to assign name and breed
Console.Write("Enter second dog's name: ");
secondDog.Name = Console.ReadLine();
Console.Write("Enter second dog's breed: ");
secondDog.Breed = Console.ReadLine(); (the example continues) 22
Dog Meeting – Example (2)
// Create a Dog with no name and breed
Dog thirdDog = new Dog();

// Save the dogs in an array


Dog[] dogs = new Dog[] { firstDog, secondDog, thirdDog };

// Ask each of the dogs to bark


foreach (Dog dog in dogs)
{
dog.SayBau();
}
}

23
CONSTRUCTORS
Defining and Using Class Constructors
What is Constructor?
■ Constructors are special methods
– Invoked/calling at the time of creating a new instance
of an object
– Used to initialize the fields of the instance
■ Constructors have the same name as the class
– Have no return type
– Can have parameters
– Can be private, protected, internal, public

25
Defining Constructors
■ Class Point with parameterless constructor:

public class Point


{
private int xCoord;
private int yCoord;

// Simple parameterless constructor


public Point()
{
this.xCoord = 0;
this.yCoord = 0;
}
// More code …
}
26
Defining Constructors (2)

public class Person // Constructor with parameters


{ public Person(string name, int age)
private string name; {
private int age; this.name = name;
this.age = age;
// Parameterless constructor
}
public Person()
{
// More code …
this.name = null;
this.age = 0;
}
}

As a rule constructors
should initialize all class
fields 27
Constructors and Initialization
■ Pay attention when using inline initialization!
public class AlarmClock
{
private int hours = 9; // Inline initialization
private int minutes = 0; // Inline initialization
// Parameterless constructor (intentionally left empty)
public AlarmClock()
{ }
// Constructor with parameters
public AlarmClock(int hours, int minutes)
{
this.hours = hours; // Invoked after the inline
this.minutes = minutes; // initialization!
}
// More code …
}
28
Chaining Constructors Calls
■ Reusing the constructors (chaining)

public class Point


{
private int xCoord;
private int yCoord;

public Point() : this(0, 0) // Reuse the constructor


{
}

public Point(int xCoord, int yCoord)


{
this.xCoord = xCoord;
this.yCoord = yCoord;
}
// More code …
}
29
METHODS
Defining and Invoking Methods
Methods
■ Methods execute some action (some code / some
algorithm)
– Could be static / per instance
– Could be public / private / protected / …
public class Point
{
private int xCoord;
private int yCoord;
public double CalcDistance(Point p)
{
return Math.Sqrt(
(p.xCoord - this.xCoord) * (p.xCoord - this.xCoord) +
(p.yCoord - this.yCoord) * (p.yCoord - this.yCoord));
}
} 31
Using Methods
■ Invoking instance methods is done through the object (through the
class instance):

class TestMethods
{
static void Main()
{
Point p1 = new Point(2, 3);
Point p2 = new Point(3, 4);
System.Console.WriteLine(p1.CalcDistance(p2));
}
}

32
PROPERTIES
Defining and Using Properties
Why We Need Properties?
■ Properties expose object's data to the world
– Control how the data is accessed / manipulated
■ Ensure the internal object state is correct
■ E.g. price should always be kept positive
■ Properties can be:
– Read-only
– Write-only
– Read and write

34
Defining Properties
■ Properties work as a pair of get / set methods
– Getter and setter
■ Properties should have:
– Access modifier (public, protected, etc.)
– Return type
– Unique name
– Get and / or Set part
– Can process data in specific way, e.g. apply validation

35
Defining Properties – Example
public class Point
{
private int xCoord;
private int yCoord;
public int XCoord
{
get { return this.xCoord; }
set { this.xCoord = value; }
}
public int YCoord
{
get { return this.yCoord; }
set { this.yCoord = value; }
}
// More code …
} 36
Dynamic Properties
■ Properties are not always bound to a class field
– Can be dynamically calculated:

public class Rectangle


{
private double width;
private double height;
public double Area
{
get
{
return width * height;
}
}
}
37
Automatic Properties
■ Properties could be defined without an underlying field
– They are automatically created by the compiler (auto properties)

class UserProfile
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

UserProfile profile = new UserProfile() {
FirstName = "Steve",
LastName = "Balmer",
UserId = 91112
};
38
KEEPING THE OBJECT STATE
CORRECT
Keep the Object State Correct
■ Constructors and properties can keep the object's state
correct
– This is known as encapsulation in OOP
– Can force validation when creating / modifying the
object's internal state
– Constructors define which properties are mandatory and
which are optional
– Property setters should validate the new value before
saving it in the object field
– Invalid values should cause an exception

40
Keep the Object State – Example
public class Person
{
private string name;
We have only one
public Person(string name)
{ constructor, so we cannot
this.Name = name; create a person without
} specifying a name
public string Name
{
get { return this.name; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Invalid name!");
this.name = value;
} Incorrect
name
}
}
cannot be assigned
41
WHAT ARE EXCEPTIONS?
The Paradigm of Exceptions in OOP
What are Exceptions?
■ The exceptions in .NET Framework / Java are a classic
implementation of the OOP exception model
■ Deliver powerful mechanism for centralized handling of
errors and unusual events
■ Substitute procedure-oriented approach, in which each
function returns error code
■ Simplify code construction and maintenance
■ Allow the problematic situations to be processed at
multiple levels

43
HANDLING EXCEPTIONS
Catching and Processing Errors
Handling Exceptions
■ In C# exceptions can be handled by the try-catch-finally construction
try
{
// Do some work that can raise an exception
}
catch (SomeException)
{
// Handle the caught exception
}
■ catch blocks can be used multiple times to process different exception types

45
Handling Exceptions – Example
static void Main()
{
string s = Console.ReadLine();
try
{
int.Parse(s);
Console.WriteLine(
"You entered a valid Int32 number {0}.", s);
}
catch (FormatException)
{
Console.WriteLine("Invalid integer number!");
}
catch (OverflowException)
{
Console.WriteLine(
"The number is too big to fit in Int32!");
}
}
46
Exception Hierarchy in .NET
System.Exception

■ Exceptions in .NET Framework are organized in a hierarchy


System.SystemException System.ApplicationException

System.NullReferenceException System.FormatException

System.ArithmeticException SofiaUniversity.InvalidStudentException

System.DivideByZeroException System.OverflowException
47
How Do Exceptions Work?
5. Throw an exception

Method N Method N
… 4. Method call … 6. Find handler

Method 2 Method 2
3. Method call 7. Find handler
Method 1 Method 1
2. Method call 8. Find handler
Main() Main()

.NET
CLR

48
ATTRIBUTES
Applying Attributes to Code Elements
What are Attributes?
■ .NET attributes are:
– Declarative tags for attaching descriptive information
in the declarations in the code
– Saved in the assembly at compile time
■ Objects derived from System.Attribute
– Can be accessed at runtime (through reflection) and
manipulated by many tools
■ Developers can define custom attributes

50
Custom Attributes – Example
[AttributeUsage(AttributeTargets.Property)]
public class MinAttribute : System.Attribute
{
public int MinValue { get; private set; }

public MinAttribute(int minValue) public class Book


{ {
public Book(string title, int copies)
this.MinValue = minValue; {
} this.Title = title;
} this.Copies = copies;
}

public string Title { get; set; }


// Example continues
[MinAttribute(0)]
public int Copies { get; set; }
}
51
Custom Attributes – Example (2)
var book = new Book("Pod Igoto", 1);
var properties = book.GetType().GetProperties();
foreach (var property in properties)
{
foreach (var attribute in property.GetCustomAttributes(false))
{
if (attribute is MinAttribute)
{
var minAttribute = (MinAttribute) attribute;
int minValue = minAttribute.MinValue;
int actualValue = (int) property.GetValue(book);

if (actualValue < minValue)


{
throw new ArgumentOutOfRangeException("Copies cannot be less than 0");
}
}
}
}
52
Interfaces – Example
Classes

Interfaces

53
Interfaces in C#
■ Interfaces in C# describe a prototype of group of
methods (operations), properties and events
– Can be implemented by a class or structure
– Define only the signature of the methods / properties
■ No concrete implementations are provided
– Can be used to define abstract data types
– Can be inherited (extended) by other interfaces
– Cannot be instantiated (can not creating new instances of
objects to be used in a program)

54
Interfaces – Example
public interface IFormatter public class JsonFormatter : IFormatter
{ {
string Format(string name); public string Format(string name)
} {
return "{\"name\":\" + name + "{0}\"}",
public class FilePrinter }
{ }
public void Print(IFormatter formatter)
{
string formatted = formatter.Format("pesho");
File.WriteAllText(formatted);
}
} public class XmlFormatter : IFormatter
{
■ Classes can implement public string Format(string name)
{
multiple interfaces return "<name>" + name + "</name>";
}
}

55

You might also like