0% found this document useful (0 votes)
43 views18 pages

C OOPS Concepts in Depth With Sample Codes 1690341231

The document provides a comprehensive overview of C# object-oriented programming concepts, including inheritance types (single, multi-level, hierarchical, and multiple inheritance), polymorphism (compile-time and run-time), and key principles such as abstraction and encapsulation. It also includes code examples demonstrating these concepts, such as method/operator overloading and the use of the base keyword. The tutorial is structured as an agenda followed by detailed explanations and sample code for each topic, aimed at teaching C# from scratch.

Uploaded by

Gaurav S
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)
43 views18 pages

C OOPS Concepts in Depth With Sample Codes 1690341231

The document provides a comprehensive overview of C# object-oriented programming concepts, including inheritance types (single, multi-level, hierarchical, and multiple inheritance), polymorphism (compile-time and run-time), and key principles such as abstraction and encapsulation. It also includes code examples demonstrating these concepts, such as method/operator overloading and the use of the base keyword. The tutorial is structured as an agenda followed by detailed explanations and sample code for each topic, aimed at teaching C# from scratch.

Uploaded by

Gaurav S
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/ 18

Agenda

❑ Inheritance in C#
❑ Single Inheritance
❑ Multi level Inheritance
❑ Hierarchical Inheritance
❑ Multiple Inheritance
❑ Compile Time Polymorphism in C#
❑ Method/Operator Overloading in C#
❑ Run-time Polymorphism in C#
❑ Importance of base keyword in C#
❑ Abstraction in C#
❑ Abstract Class
❑ Abstract Method
❑ Non Abstract Method
❑ Encapsulation in C#
Learn C# or C-Sharp from Scratch

C# OOPS Tutorial In-Depth

Trainer – Haradhan Pal


2
Inheritance in C#
❑ Inheritance is a feature of object-oriented programming (OOP) languages that allows user to define a
base class that provides specific functionality (data and behavior) and to define derived classes that
either inherit or override that functionality.
❑ Using Inheritance user can create Classes that are built in upon existing classes.
❑ When user Inherit from an existing class, then they can reuse Methods and fields from Parent class
and can add new methods and fields as well.
❑ The class where the class members are getting Inherited is called as Super class/Parent class/Base
class.
❑ The class to which the class members are getting Inherited is called as Sub class/Child class/Derived
class.
❑ To inherit from a class, user can use the : symbol
Types of Inheritance in C#:
1) Single Inheritance:
A single derived class inherits from a single base class
public class ClassB : ClassA {
}
2) Multi level Inheritance:
A derived class inherits from a base and then the same derived class acts as a base class for another class.
public class ClassB : ClassA {
}
public class ClassC : ClassB {
}
Types of Inheritance in C#

3) Hierarchical Inheritance:
One class serves as a superclass (base class) for more than one subclass.

4) Multiple Inheritance (Through Interfaces Only) :


One class can have more than one superclass and inherit features from all parent
classes. As C# does not support multiple inheritance with classes, user can achieve
multiple inheritance only through Interfaces in C#.
C# Single and Multi-level Inheritance
public class ClassA
{ public int a = 20;
public void add(int x, int y)
{
Console.WriteLine(x + y);
}}
public class ClassB : ClassA
{ public int b = 30;
public void substraction(int x, int y)
{
Console.WriteLine(x - y);
}}
public class ClassC : ClassB
{ public int c = 30;
public void multiplication(int x, int y)
{
Console.WriteLine(x * y);
}}

static void Main() {


ClassA objA = new ClassA();
Console.WriteLine(objA.a); objA.add(10, 20);
ClassB objB = new ClassB();
Console.WriteLine(objB.a); objB.add(30, 20);
Console.WriteLine(objB.b); objB.substraction(30, 20);
ClassC objC = new ClassC();
Console.WriteLine(objC.a); objC.add(30, 20);
Console.WriteLine(objC.b); objC.substraction(30, 20);
Console.WriteLine(objC.c); objC.multiplication(30, 20);
}
Compile Time Polymorphism in C#
❑ Polymorphism is one of the features provided by Object Oriented Programming. It simply means occurring in more than one form.
In other word, the same entity (method or operator) can perform different operations in different scenarios.
❑ Polymorphism derived from two Greek words, Poly-means Many and Morphs - means ways; So polymorphism means many ways.
❑ There are two types of Polymorphism is available in C#.
a) Static/Compile Time Polymorphism (Method/Operator Overloading)
b) Dynamic/Run-Time Polymorphism (Method Overriding)
❑ Method Overloading: Two are more methods having same name in the same class but they differ in following ways.
a) Number of Arguments
b) Type of Arguments
c) Order of Arguments
Example for Method Overloading by changing the no and data type of Arguments:
public class MethodOverLoading {
public void add(int a, int b){
Console.WriteLine(a+b);
}
public void add(int a, int b, int c){
Console.WriteLine(a+b+c);
}
public void add(double a, double b){
Console.WriteLine(a+b);
}
static void Main() {
MethodOverLoading obj = new MethodOverLoading();
obj.add(100, 200);
obj.add(15, 25, 35);
obj.add(101.234, 23.456);
}}
Method Overloading in C#
Example for Method Overloading by changing the order of Arguments:
class Program {
public void studentIdentity(String name, int id)
{
Console.WriteLine("Name1 : " + name + ", "
+ "Id1 : " + id);
}
public void studentIdentity(int id, String name)
{
Console.WriteLine("Name2 : " + name + ", "
+ "Id2 : " + id);
}

static void Main()


{
Program obj = new Program();
obj.studentIdentity("Rahul", 1);
obj.studentIdentity(2, "Rajesh");
}
}
Operator Overloading in C#
❑ Operator Overloading: Some operators in C# behave differently with different operands.
For example, + operator is overloaded to perform numeric addition as well as string
concatenation.
Example for Operator Overloading:
public class MethodOverLoading {
public int add(int a, int b){
int result = a+b;
return result;
}
public string add(string a, string b){
string result = a+b;
return result;
}

static void Main() {


MethodOverLoading obj = new MethodOverLoading();
Console.WriteLine(obj.add(10, 20)); //30
Console.WriteLine(obj.add("Hello ", "C#")); //Hello C#
}}
Run-time Polymorphism in C#
❑ If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in C#. It
is used to achieve runtime polymorphism. It enables user to provide specific implementation of the method which is
already provided by its base class.
❑ 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.

Example:
Public class Animal{
//Overridden method
public void eat()
{
Console.WriteLine(“Animal is eating");
}}
Public class Tiger : Animal{
//Overriding method
public void eat(){
Console.WriteLine("Tiger is eating");
}
static void Main() {
Tiger obj = new Tiger();
//This will call the child class version of eat()
obj.eat();
}
} //Output: Tiger is eating
Importance of base keyword in C#
❑ The base keyword in C# is a reference variable which is used to refer immediate parent class
object.
❑ Whenever user create the instance of subclass, an instance of parent class is created implicitly
which is referred by base reference variable.
❑ base keyword can be used at variable, method and constructor level.
Example:
public class Animal{
public string name=“Elephant";
}
public class Dog : Animal{
public string name=“Bullet";
public void printName(){
Console.WriteLine(Name);//prints Name of Dog class
Console.WriteLine(base.Name);//prints Name of Animal class
}
}
static void Main() {
Dog d=new Dog();
d.printName();
}
Abstraction in C#
❑ Abstraction is a process of hiding implementation details and showing only
functionality to the user.
❑ In another way it shows important things to the user and hides internal details, for
example, sending SMS where user type the text and send the message. One don't
know the internal processing about the message delivery.
❑ Abstraction focuses on what the Object does instead of how it does. Abstraction can
be achieved with either abstract classes or interfaces.
❑ A class which is declared with the abstract keyword is known as an abstract class in
C#. It can have abstract and non-abstract methods (method with the body).
❑ It is not possible to create an object of the abstract class.
❑ The abstract keyword enables user to create classes and class members that are
incomplete and must be implemented in a derived class.
❑ The purpose of an abstract class is to provide a common definition of a base class
that multiple derived classes can share.
❑ Abstract methods have no implementation, so the method definition is followed by a
semicolon instead of a normal method block. Derived classes of the abstract class
must implement all abstract methods.
❑ User can not declare the abstract methods outside the abstract class.
Abstraction Example in C#
Example:
abstract class Animal
{
public abstract void eat();
public void drink()
{
Console.WriteLine("Animal used to drink Water");
}
}
class Tiger : Animal
{
public override void eat()
{
Console.WriteLine("Tiger used to eat meat");
}
}

static void Main()


{
Tiger obj = new Tiger();
obj.eat();
obj.drink();
//Animal animal = new Animal(); // Error CS0144 Cannot create an instance of the abstract type or interface 'Animal
}
C# Encapsulation
❑ Encapsulation is one of the basic features of object-oriented programming (OOP) languages.
❑ 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.
❑ Encapsulation allows user to create a level of abstraction between the internal workings of an object and
its external behavior. This makes it easier to understand the code and reduces the risk of errors caused by
changing the internal data directly.
❑ Variables or data of a class are hidden from any other class in encapsulation and can be accessed only
through any member function of its own class in which they are declared. The data in a class is hidden
from other classes in Encapsulation, so it is also known as data-hiding.
❑ Private access specifier allows a class to hide its member variables and member functions from other
functions and objects. Only functions of the same class can access its private members. 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.
❑ User declare variables as private to stop accessing them directly from outside the class. The public setter
and getter methods or public properties are used to access the private variables from outside the class
with proper validations. In case user provide direct access to the variables of a class then they cannot
validate the data before storing it in the variable or while retrieving the data stored in the variable.
❑ Encapsulation makes the code more maintainable, flexible, and secure by providing a way to control
access to the internal data of an object, creating a level of abstraction, and making the code more
modular.
❑ One of the real-world examples of encapsulation is Capsule, as capsule binds all its medicinal materials
within it, similarly in C# encapsulation units (class, interface, enums, structs, etc) encloses all its data
member and member functions within it. Another real-world example of encapsulation can be school or
office bag. The bag contains different stuff like Pen, Pencil, Book, Notebook, etc within it.
C# Inheritance Sample Code
public class ClassA
{
public int a = 20;
public void add(int x, int y)
{
Console.WriteLine(x + y);
}
}

public class ClassD : ClassA


{
public int d = 50;
public void division(int x, int y)
{
Console.WriteLine(x/y);
}
}

public class ClassB : ClassA


{
public int b = 30;
public void substraction(int x, int y)
{
Console.WriteLine(x - y);
}
}

public class ClassC : ClassB


{
public int c = 30;
public void multiplication(int x, int y)
{
Console.WriteLine(x * y);
}
}
ClassA objA = new ClassA();
Console.WriteLine(objA.a);
objA.add(10, 20);

ClassB objB = new ClassB();


Console.WriteLine(objB.a);
objB.add(30, 20);
Console.WriteLine(objB.b);
objB.substraction(30, 20);
// Console.WriteLine(objB.a); error while accessing Class a variable without Inheritance

ClassC objC = new ClassC();


Console.WriteLine(objC.a);
objC.add(30, 20);
Console.WriteLine(objC.b);
objC.substraction(30, 20);
Console.WriteLine(objC.c);
objC.multiplication(30, 20);
ClassD objD = new ClassD();
Console.WriteLine(objD.a);
objD.add(30, 20);
Console.WriteLine(objD.d);
objD.division(30, 10);
C# Compile Time Polymorphism Sample Code
public int plusMethod(int i, int j)
{
int result = i + j;
return result;
}
public string plusMethod(string i, string j)
{
string result = i + j;
return result;
}

public void studentIdentity(String studentName, int rollNo)


{
Console.WriteLine("Name1: "+ studentName+ " ," + "Roll1: "+ rollNo);
}
public void studentIdentity(int rollNo, String studentName)
{
Console.WriteLine("Name2: " + studentName + " ," + "Roll2: " + rollNo);
}
public void add(int a, int b) {
Console.WriteLine(a+b);
}
public void add(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
public void add(double a, double b)
{
Console.WriteLine(a + b);
}

Program obj = new Program();

Console.WriteLine(obj.plusMethod(23, 34)); //57


Console.WriteLine(obj.plusMethod("Learn C# ", "from Scratch")); //Learn C# from Scratch

obj.add(20, 25);
obj.add(10, 30, 50);
obj.add(200.34, 300.988);
obj.studentIdentity("Rahul", 2);
obj.studentIdentity(4, "Rajesh");

public class MethodOverLoading {


public void add(int a, int b){
Console.WriteLine(a+b);
}
public void add(int a, int b, int c){
Console.WriteLine(a+b+c);
}
public void add(double a, double b){
Console.WriteLine(a+b);
}
static void Main() {
MethodOverLoading obj = new MethodOverLoading();
obj.add(100, 200);
obj.add(15, 25, 35);
obj.add(101.234, 23.456);
}}

public int add(int a, int b)


{
int result = a + b;
return result;
}

public string add(string a, string b)


{
string result = a + b;
return result;
}
public void studentIdentity(String name, int id)
{

Console.WriteLine("Name1 : " + name + ", "


+ "Id1 : " + id);
}
public void studentIdentity(int id, String name)
{

Console.WriteLine("Name2 : " + name + ", "


+ "Id2 : " + id);
}

Program obj = new Program();


obj.studentIdentity("Rahul", 1);
obj.studentIdentity(2, "Rajesh");

Console.WriteLine(obj.add(1, 2));
Console.WriteLine(obj.add("Hello ", "C#"));
C# Run Time Polymorphism Sample Code
public class Animal

{
public Animal() {
Console.WriteLine("Animal Class Constructor");
}
public string name ="Elephant";
//Overridden method
public void eat()
{
Console.WriteLine("Animal is eating");
}
}
public class Tiger : Animal
{
public Tiger() : base()
{
}
/*public Tiger()
{
Console.WriteLine("Tiger Class Constructor");
} */
public string name = "Royal Bengal Tiger";

public void printName()


{
//Console.WriteLine(name);//prints Name of Tiger class
Console.WriteLine(base.name);//prints Name of Animal class

//Overriding method
public void eat()
{
Console.WriteLine("Tiger is eating");
}

public void eatParentClass()


{
base.eat();
}
}
Animal animal = new Animal(); //Base class constructor will be called
// animal.eat();
Tiger obj = new Tiger(); //Both Base class and subclass constructor will be called
//This will call the child class version of eat()
obj.eat();
obj.eatParentClass();

obj.printName();
C# Abstraction Sample Code
abstract class Animal
{
public abstract void eat();
public abstract void run(); //Create later after one run
public void drink()
{
Console.WriteLine("Animal used to drink Water");
}
}
class Tiger : Animal
{
public override void eat()
{
Console.WriteLine("Tiger used to eat meat");
}
public override void run()
{
Console.WriteLine("Tiger used to run fast");
}
}

static void Main()


{
Tiger obj = new Tiger();
obj.eat();
obj.drink();
obj.run();
//Animal animal = new Animal(); // Error CS0144 Cannot create an instance of the abstract type or interface 'Animal'
Console.ReadKey();
}
C# Encapsulation Sample Code
using System;

class Student
{
private int StudentRollNo; //these private variables can only be accessed by public methods of class
private string studentName;
private int studentAge;

//Creating public Setter and Getter methods, This method is used to return the data stored in the StudentRollNo variable
public int sRollNo
{
get { return StudentRollNo; }

set { StudentRollNo = value; }


}
public String sName
{

get { return studentName; }

set { studentName = value; }


}
public int sAge
{
get { return studentAge; }

set { studentAge = value; }


}
}

class Program
{
static void Main()
{
Student student = new Student();

//User can access the private variable via public setter and getter methods

student.sRollNo = 1;
student.sName = "Rahul";
student.sAge = 10;
Console.WriteLine("Student Roll No : " + student.sRollNo);
Console.WriteLine("Student Name : " + student.sName);
Console.WriteLine("Student Age : " + student.sAge);

//Console.WriteLine(student.StudentRollNo); //User cannot access the Private Variable directly and it will throw Compile Time Error

Console.ReadKey();
}
}

You might also like