Window Programming Ch3 C# OO Concepts Modified
Window Programming Ch3 C# OO Concepts Modified
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;
}
}
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
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>])
Output:
The sum is: 35
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.
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
Output:
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.
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
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