0% found this document useful (0 votes)
56 views12 pages

Window Programming Ch3 C# OO Concepts Modified

The document discusses several key object-oriented programming concepts in C#: 1. Inheritance allows one class to inherit features from another superclass, enabling code reuse. A subclass inherits fields and methods from its parent class. 2. Encapsulation wraps data within a class and controls access to it via accessors (getters and setters). This hides implementation details and increases flexibility and testability. 3. Abstraction displays only essential details to the user and hides irrelevant implementation. It is achieved through abstract classes, which can contain abstract and overridden methods. 4. Methods are reusable blocks of code that perform tasks and can return values. They increase readability and reduce duplicate code through parameterization.

Uploaded by

Abdurezak Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
56 views12 pages

Window Programming Ch3 C# OO Concepts Modified

The document discusses several key object-oriented programming concepts in C#: 1. Inheritance allows one class to inherit features from another superclass, enabling code reuse. A subclass inherits fields and methods from its parent class. 2. Encapsulation wraps data within a class and controls access to it via accessors (getters and setters). This hides implementation details and increases flexibility and testability. 3. Abstraction displays only essential details to the user and hides irrelevant implementation. It is achieved through abstract classes, which can contain abstract and overridden methods. 4. Methods are reusable blocks of code that perform tasks and can return values. They increase readability and reduce duplicate code through parameterization.

Uploaded by

Abdurezak Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

C# Object Oriented Concepts

C# Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in
C# by which one class is allowed to inherit the features (fields and methods) of another class.
Important terminology:
 Super Class: The class whose features are inherited is known as super class (or a base
class or a parent class).
 Sub Class: The class that inherits the other class is known as subclass (or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
The symbol used for inheritance is:
Syntax:
class derived-class : base-class
{
// methods and fields
}
Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Inheritance
{
// base class
class SuperClass {
// Data members
public string name;
public string subject;
public void Super(string name, string subject)
{
this.name = name;
this.subject = subject;
Console.WriteLine("My name is: " + name);
Console.WriteLine("My Favorite Subject is: " + subject);
}
}
// derived class
class InheritClass : SuperClass {
// this is a constructor of derived class
public InheritClass()
{
Console.WriteLine("InheritClass");
}
}
// driver class
class Inheritance {
static void Main(string[] args)
{
// creating object of derived class
InheritClass h = new InheritClass();
h.Super("Dawit", "C#");
Console.ReadKey();
}
}
}
Output:
My name is: Dawit
My Favorite Subject is: C#

C# Encapsulation
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. In a different way, encapsulation is a protective
shield that prevents the data from being accessed by the code outside this shield.
 Technically in encapsulation, the variables or data of a class are hidden from any other
class and can be accessed only through any member function of own class in which they
are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class as private and
using C# Properties in the class to set and get the values of variables.
Example:
using System;

namespace Encapsulation
{
public class Encap {
private String studentName;
private int studentAge;
// using accessors to get & set the value of studentName
public String Name
{
get
{
return studentName;
}
set
{
studentName = value;
}
}

// using accessors to get & set the value of studentAge


public int Age
{
get
{
return studentAge;
}
set
{
studentAge = value;
}
}
}
// Driver Class
class Driver
{
static public void Main()
{
Encap obj = new Encap();
obj.Name = "Chaltu";
obj.Age = 20;

Console.WriteLine("Name: " + obj.Name);


Console.WriteLine("Age: " + obj.Age);
Console.ReadKey();
}
}
}
Output:
Name: Chaltu
Age: 20
Explanation: In the above program the class Encap is encapsulated as the variables are declared
as private. To access these private variables we are using the Name and Age accessors which
contains the get and set method to retrieve and set the values of private fields. Accessors are
defined as public so that they can access in other class.
Advantages of Encapsulation:
 Data Hiding: The user will have no idea about the inner implementation of the class. It
will not be visible to the user that how the class is stored values in the variables. He only
knows that we are passing the values to accessors and variables are getting initialized to
that value.
 Increased Flexibility: We can make the variables of the class as read-only or write-only
depending on our requirement. If we wish to make the variables as read-only then we have
to only use Get Accessor in the code. If we wish to make the variables as write-only then
we have to only use Set Accessor.
 Reusability: Encapsulation also improves the re-usability and easy to change with new
requirements.
 Testing code is easy: Encapsulated code is easy to test for unit testing.

C# Abstraction
Data Abstraction is the property by virtue of which only the essential details are exhibited to the
user. The trivial or the non-essentials units aren’t exhibited to the user. Data Abstraction may
also be defined as the process of identifying only the required characteristics of an object
ignoring the irrelevant details. The properties and behaviors of an object differentiate it from
other objects of similar type and also help in classifying/grouping the objects.
Example: Consider a real-life scenario of withdrawing money from ATM. The user only knows
that in ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter
the amount which he/she wants to withdraw and at last, he/she gets their money. The user does
not know about the inner mechanism of the ATM or the implementation of withdrawing money
etc. The user just simply know how to operate the ATM machine, this is called abstraction. In C#
abstraction is achieved with the help of Abstract classes.

Abstract Classes
 An abstract class is declared with the help of abstract keyword.
 In C#, you are not allowed to create objects of the abstract class. Or in other words, you
cannot use the abstract class directly with the new operator.
 Class that contains the abstract keyword with some of its methods (not all abstract method)
is known as an Abstract Base Class.
 Class that contains the abstract keyword with all of its methods is known as pure Abstract
Base Class.
 You are not allowed to declare the abstract methods outside the abstract class.
 You are not allowed to declare abstract class as Sealed Class.
Example:
using System;

namespace Abstraction
{
// abstract class
abstract class Shape
{
// abstract method
public abstract int area();
}
// square class inherting the Shape class
class Square : Shape
{
// private data member
private int side;
// method of square class
public Square(int x = 0)
{
side = x;
}
// overriding of the abstract method of Shape class using the override keyword
public override int area()
{
Console.Write("Area of Square: ");
return (side * side);
}
}
// Driver Class
class Driver
{
static void Main(string[] args)
{
// creating reference of Shape class which refer to Square class instance
Shape sh = new Square(4);
// calling the method
double result = sh.area();
Console.Write("{0}", result);
Console.ReadKey();
}
}
}
Output:

Area of Square: 16

Encapsulation vs Data Abstraction

 Encapsulation is data hiding (information hiding) while Abstraction is detail hiding


(implementation hiding).
 While encapsulation groups together data and methods that act upon the data, data abstraction deals
with exposing to the user and hiding the details of implementation.
Advantages of Abstraction
 It reduces the complexity of viewing the things.
 Avoids code duplication and increases reusability.
 Helps to increase security of an application or program as only important details are provided to
the user.

C# Methods
Methods are generally the block of codes or statements in a program that gives the user the
ability to reuse the same code which ultimately saves the excessive use of memory, acts as
a time saver and more importantly, it provides a better readability of code. So basically, a
method is a collection of statements that perform some specific task and return the result to the
caller. A method can also perform some specific task without returning anything.
Example :
static double GetCircleArea(double radius)
{
const float pi = 3.14F;
double area = pi * radius * radius;
return area;
}
Method declaration means the way to construct method including its naming.
Syntax :
<Access_Modifier> <return_type> <method_name>([<param_list>])

Example: In the code below, a method named Sum() is called.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MethodImpl
{
class Add
{
static int Sum(int x, int y)
{
int a = x;
int b = y;
int result = a + b;
return result;
}
static void Main(string[] args)
{
int a = 12;
int b = 23;
int c = Sum(a, b);

Console.WriteLine("The sum is: " + c);


Console.ReadKey();
}
}
}

Output:
The sum is: 35

Example 2: Method With Parameters & With Return Value Type

using System;
namespace Factorial
{
class Factorial
{
// This method asks a number from the user and using that it
// calculates the factorial of it and returns the result
static int factorial(int n)
{
int f = 1;
// Method to calculate the factorial of a number
for (int i = 1; i <= n; i++)
{
f = f * i;
}
return f;
}
static void Main(string[] args)
{
Console.WriteLine("enter the number to know its Factorial:");
int p = int.Parse(Console.ReadLine());
// displaying result by calling the function
Console.WriteLine("Factorial is : " + factorial(p));
Console.ReadKey();
}
}
} Enter the number to know its Factorial:
Output : 4
Factorial is : 24
Advantages of using the Methods:
 It makes the program well structured.
 Methods enhance the readability of the code.
 It provides an effective way for the user to reuse the existing code.
 It optimizes the execution time and memory space.

C# Method Overriding
Method Overriding is a technique that allows the invoking of functions from another class (base
class) in the derived class. Creating a method in the derived class with the same signature as a
method in the base class is called as method overriding.
When a method in a subclass has the same name, same parameters or signature and same return
type(or sub-type) as a method in its super-class, then the method in the subclass is said to
override the method in the super-class. Method overriding is one of the ways by which C#
achieve Run Time Polymorphism (Dynamic Polymorphism).
The method that is overridden by an override declaration is called the overridden base method.
An override method is a new implementation of a member that is inherited from a base class.
The overridden base method must be virtual, abstract, or override.

Syntax: class base_class


{
public void myMethod();
}
class derived_class : base_class
{
public void myMethod();
}
class Main_Method
{
static void Main()
{
derived_class d = new derived_class();
d. myMethod();
}
}
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MOverride
{
class B
{
public virtual void MyMethod() // Virtual method; Gives runtime error if you
remove this method
{
Console.WriteLine("This is the Family");
Console.ReadKey();
}
}

class D : B
{
public override void MyMethod() // Overriding virtual method
{
Console.WriteLine("This is the Child");
Console.ReadKey();
}
}

class Program
{
static void Main()
{
B msg = new B();
msg.MyMethod(); // This will call the B method

msg = new D();


msg.MyMethod(); // This will call the D method
}
}
}

Output:

This is the Family


This is the Child
Note:
Method overriding is possible only in derived classes. Because a method is overridden in
the derived class from base class.
A method must be a non-virtual or static method for override.
Both the override method and the virtual method must have the same access level
modifier.
C# Method Overloading
Method Overloading is the common way of implementing polymorphism. It is the ability to
redefine a function in more than one form. A user can implement function overloading by
defining two or more functions in a class sharing the same name. C# can distinguish the methods
with different method signatures. i.e. the methods can have the same name but with different
parameters list (i.e. the number of the parameters, order of the parameters, and data types of the
parameters) within the same class.

 Overloaded methods are differentiated based on the number and type of the parameters
passed as arguments to the methods.
 You cannot define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.
 The compiler does not consider the return type while differentiating the overloaded
method. But you cannot declare two methods with the same signature and different return
type. It will throw a compile-time error. If both methods have the same parameter types,
but different return type, then it is not possible.

Different ways of doing overloading methods


1. The number of parameters in two methods.
2. The data types of the parameters of methods.
3. The Order of the parameters of methods.

1. By changing the Number of Parameters


using System;

namespace Moverload1
{
// C# program to demonstrate the function
// overloading by changing the Number
// of parameters
class Overload
{
// adding two integer values.
public int Add(int a, int b)
{
int sum = a + b;
return sum;
}
// adding three integer values.
public int Add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}
// Main Method
public static void Main(String[] args)
{
// Creating Object
Overload ob = new Overload();
int sum1 = ob.Add(1, 2);
Console.WriteLine("sum of the two integer value : " + sum1);
int sum2 = ob.Add(1, 2, 3);
Console.WriteLine("sum of the three integer value : " + sum2);
Console.ReadKey();
}
}
}
Output:
sum of the two integer value : 3
sum of the three integer value : 6

2. By changing the Data types of the parameters


using System;

namespace Moverload2
{
// C# program to demonstrate the function
// overloading by changing the Data types
// of the parameters
class Moverload
{
// adding three integer values.
public int Add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}
// adding three double values.
public double Add(double a, double b, double c)
{
double sum = a + b + c;
return sum;
}
public static void Main(String[] args)
{
// Creating Object
Moverload ob = new Moverload();
int sum2 = ob.Add(1, 2, 3);
Console.WriteLine("sum of the three integer value : " + sum2);
double sum3 = ob.Add(1.0, 2.0, 3.0);
Console.WriteLine("sum of the three double value : " + sum3);
Console.ReadKey();
}
}
}
Output:
sum of the three integer value : 6
sum of the three double value : 6
3. By changing the Order of the parameters
using System;

namespace Moverload3
{
// C# program to demonstrate the function
// overloading by changing the
// Order of the parameters
class Overload3
{
// Method
public void Identity(String name, int id)
{
Console.WriteLine("Name : " + name + ", " + "Id : " + id);
}
// Method
public void Identity(int id, String name)
{
Console.WriteLine("Name : " + name + ", " + "Id : " + id);
}
// Main Method
public static void Main(String[] args)
{
// Creating Object
Overload3 obj = new Overload3();
obj.Identity("Akkasa ", 1);
obj.Identity("Akkashe ", 2);
Console.ReadKey();
}
}
}

Output:
Name : Akkasa Id : 1
Name : Akkashe Id : 2

You might also like