0% found this document useful (0 votes)
22 views36 pages

T3 - C# - Chương 4 - OOP

This document covers Object-Oriented Programming concepts, including class declaration, access modifiers, encapsulation, inheritance, polymorphism, and interfaces in C#. It provides examples and explanations of key features such as constructors, properties, static classes, extension methods, and record types. Additionally, it discusses the use of 'is' and 'as' operators, readonly members, and object initializers.
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)
22 views36 pages

T3 - C# - Chương 4 - OOP

This document covers Object-Oriented Programming concepts, including class declaration, access modifiers, encapsulation, inheritance, polymorphism, and interfaces in C#. It provides examples and explanations of key features such as constructors, properties, static classes, extension methods, and record types. Additionally, it discusses the use of 'is' and 'as' operators, readonly members, and object initializers.
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/ 36

Chap 4

Object-Oriented Programming
Ph.D Luu Thi Bich Huong

@CMC UNI 2024


Content
4.1. Class declaration
4.2. Declare constants, variables and ranges
4.3. Declare functions and ranges (private, protected, public),
static functions. get/set functions
4.4. Using single inheritance classes, abstraction classes,
overloading, overrides, and polymorphs
4.5. Using interfaces, solutions to create multiple inheritances

@CMC UNI 2024


Class declaration
[access_modifier] class ClassName
{
// Fields (biến thành viên)
[access_modifier] DataType fieldName;
// Properties
[access_modifier] DataType PropertyName { get; set; }
// Constructor
[access_modifier] ClassName()
{
// Khối mã khởi tạo đối tượng
}
// Methods
[access_modifier] ReturnType MethodName(ParameterList)
{
// Khối mã thực thi của phương thức
}
// Other members: events, indexers, etc.
}

@CMC UNI 2024


Class declaration
• [access_modifier]: public, private, protected, or internal.
• class ClassName: name Class.
• DataType fieldName;: Declares a field with the data type
DataType.
• DataType PropertyName {get; set;}: Declares a property with
the data type DataType.
• ClassName() { }: Declares a constructor to initialize an object of
the class.
• ReturnType MethodName(ParameterList) { }: Declares a
method with the return type ReturnType and parameters
ParameterList.

@CMC UNI 2024


Access_modifier
There are five access specifiers: private, public, protected, internal,
and protected internal. By default, the members are private to the
class
▪ public: The type or member can be accessed by any other code in
the same assembly or another assembly that references it
▪ private: The type or member can be accessed only by code in the
same class or struct
▪ protected: The type or member can be accessed only by code in
the same class, or in a class that is derived from that class

6/11/2024 5
@CMC UNI 2024
Access_modifier
▪ internal: The type or member can be accessed by any code in
the same assembly, but not from another assembly
▪ protected internal: The type or member can be accessed by

any code in the assembly in which it's declared, or from within


a derived class in another assembly
▪ private protected: The type or member can be accessed only

within its declaring assembly, by code in the same class or in


a type that is derived from that class

6/11/2024 6
@CMC UNI 2024
Example
using System;
public class Person
{ // Method
// Fields public void DisplayInfo()
private string name; {
private int age;
Console.WriteLine($"Name: {Name}, Age: {Age}"); }
// Property
// Static method
public static void Greet()
public string Name
{
{
Console.WriteLine("Hello from the Person
get { return name; }
class!"); }
set { name = value; } }
}
public int Age
class Program
{
{
get { return age; }
static void Main(string[] args)
set { age = value; } }
{
// Constructor
// Create Person object
public Person() Person person1 = new Person();
{ Person person2 = new Person("John Doe", 30);
name = "Unknown"; // Call DisplayInfo method
age = 0; } person1.DisplayInfo();
public Person(string name, int age) person2.DisplayInfo();
{ // Call static Greet method
this.name = name; Person.Greet(); }}
this.age = age; }

@CMC UNI 2024


Explanation of the Example
• Fields: private string name; and private int age; are the class
member variables.
• Properties: public string Name { get; set; } and public int Age {
get; set; } are properties for accessing and modifying the
member variables.
• Constructors: public Person() is the default constructor and
public Person(string name, int age) is a constructor with
parameters.
• Methods: public void DisplayInfo() is a method to display the
object's information and public static void Greet() is a static
method to display a greeting

@CMC UNI 2024


OOP-Encapsulation
◆ Encapsulation is defined as binding data and code that manipulates it
together in a single unit

◆ Data is privately bound within a class without direct access from the
outside of the class

◆ All objects that need to read or modify the data of an object should do it
through the public methods that a class provides

◆ This characteristic is called data hiding and makes code less error-prone
by defining a limited number of entry points to an object’s data

6/11/2024 9
@CMC UNI 2024
OOP-Encapsulation

6/11/2024 10
@CMC UNI 2024
Read-only auto properties & Init-Only properties

• When we write a property only with "get", it automatically becomes a Read


Only property or we can use Init-Only properties

6/11/2024 11
@CMC UNI 2024
OOP-Inheritance
◆ Inheritance is a mechanism through which a class can inherit the
properties and functionalities of another class
◆ Other classes can inherit these functionalities and data of the
parent class as well as extending or modifying them and adding
additional functionalities and properties.
◆ There are three types of inheritance supported in C#:

6/11/2024 12
@CMC UNI 2024
OOP-Inheritance

6/11/2024 13
@CMC UNI 2024
OOP-Polymorphism
◆ Ability allows many versions of a method based on overloading
and overriding methods techniques

6/11/2024 14
@CMC UNI 2024
virtual : provide a default implementation. Can
be overridden if necessary

abstract: sub-classes MUST override

Besides virtual and abstract, C# provide new


keyword that applies to methods. What does
that mean?
6/11/2024 15
@CMC UNI 2024
OOP-Interface
◆ An interface contains definitions for a group of related functionalities that a
non-abstract class or a struct must implement
◆ An interface cannot be instantiated but can only be inherited by classes or
other interfaces
◆ An interface may not declare instance data such as fields, auto-implemented
properties, or property-like events. Interface names begin with a capital “I”

6/11/2024 16
@CMC UNI 2024
OOP-Interface

6/11/2024 17
@CMC UNI 2024
Interface Inheritance

6/11/2024 18
@CMC UNI 2024
Default Interface Methods
• C# allows to add a method with their implementation to the
interface without breaking the existing implementation of the
interface, such type of methods is known as default interface
methods(virtual extension methods)

6/11/2024 19
@CMC UNI 2024
The is and as Operators
◆ The is operator is used to check if the run-time type of an object is
compatible with the given type or not whereas as operator is used to
perform conversion between compatible reference types or Nullable types
◆ The is operator returns true if the given object is of the same type
whereas as operator returns the object when they are compatible with the
given type
◆ The is operator returns false if the given object is not of the same type
whereas as operator return null if the conversion is not possible
◆ The is operator is used for only reference, boxing, and unboxing
conversions whereas as operator is used only for nullable, reference and
boxing conversions
6/11/2024 20
@CMC UNI 2024
The is and as Operators

6/11/2024 21
@CMC UNI 2024
Static Constructor
◆ Prevent static field to be reset
◆ A given class (or structure) may
define only a single static constructor
◆ A static constructor executes exactly
one time, regardless of how many
objects of the type are created
◆ A static constructor does not take an
access modifier and cannot take any
parameters
◆ The static constructor executes
before any instance-level constructors
6/11/2024 22
@CMC UNI 2024
Static Class
◆ Classes that cannot be instantiated or inherited are known as
classes and the static keyword is used before the class name that
consists of static data members and static methods
◆ It is not possible to create an instance of a static class using the

new keyword. The main features of static classes are as follows:


▪ They can only contain static members
▪ They cannot be instantiated or inherited and cannot contain
instance constructors. However, the developer can create static
constructors to initialize the static members

6/11/2024 23
@CMC UNI 2024
Static Class

No instance created

6/11/2024 24
@CMC UNI 2024
Extension Method
◆ Extension methods allow you to extend an existing type with
new functionality without directly modifying those types
◆ Extension methods are static methods that have to be
declared in a static class
◆ We can declare an extension method by specifying the first
parameter with the this keyword
◆ The first parameter in this method identifies the type of
objects in which the method can be called
◆ The object that we use to invoke the method is automatically
passed as the first parameter
6/11/2024 25
@CMC UNI 2024
Extension Method

6/11/2024 26
@CMC UNI 2024
Expression-bodied Members
◆ Expression body definitions let you provide a member's
implementation in a very concise, readable form
◆ We can use an expression body definition whenever the
logic for any supported member, such as a method or
property, consists of a single expression
◆ An expression body definition has the following general
syntax: member => expression;

◆ Members can be: Method, Read-only property, Property,


Constructor, Finalizer and Indexer
6/11/2024 27
@CMC UNI 2024
Expression-bodied Members

6/11/2024 28
@CMC UNI 2024
Anonymous Type
◆ Is basically a class with no name and is not explicitly defined in code
◆ Uses object initializers to initialize properties and fields. Since it has no name,
we need to declare an implicitly typed variable to refer to it
◆ Anonymous types are class types that derive directly from object, and that
cannot be cast to any type except object

6/11/2024 29
@CMC UNI 2024
Object Initialize
◆ Object initializers let we assign values to any accessible fields or
properties of an object at creation time without having to invoke a
constructor followed by lines of assignment statements
◆ The object initializer syntax enables you to specify arguments for a
constructor or omit the arguments
class Customer {
public string Name { get; set; }
public int Age { get; set; }
}

Customer c = new Customer(); Can be combined with any


c.Name = "Jack"; constructor call
c.Age = 20;

var c = new Customer(){ Name = "Jack", Age = 20};


6/11/2024 30
@CMC UNI 2024
Readonly member and const keyword

◆ In a field declaration, readonly indicates that assignment to the


field can only occur as part of the declaration or in a constructor in
the same class

◆ A readonly field can't be assigned after the constructor exits

◆ A const field can only be initialized at the declaration of the field(a


compile-time constant)

◆ A readonly field can be assigned multiple times in the field


declaration and in any constructor(a run-time constants)
6/11/2024 31
@CMC UNI 2024
Readonly member and const keyword

6/11/2024 32
@CMC UNI 2024
Record type
◆ Records type is a new reference type that we can create instead of classes
or structs
◆ Records are distinct from classes in that record types use value-based
equality
◆ We define a record by declaring a type with the record keyword

6/11/2024 33
@CMC UNI 2024
Record type

6/11/2024 34
@CMC UNI 2024
Using Declarations
• With the using declaration, the objects are disposed
automatically. Its scope is automatically defined from the object’s
declaration statement to the end of the current code block

6/11/2024 35
@CMC UNI 2024
THANK YOU

@CMC UNI 2024 36

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy