0% found this document useful (0 votes)
18 views

Module 2

Uploaded by

mr.arjunb27
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module 2

Uploaded by

mr.arjunb27
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Department of MCA
Advanced Programming -21MCA3041
Module 2: Classes, Objects and Object Oriented
Programming
Handling By
Nirupama K
Asst. Prof. Dept. of MCA
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Classes and objects
• Everything in C# is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
• Classes: it allow you to control all the functions that can be applied to a given set of data as well
as how to access the data
• Creating class:
Syntax: Class <classname>
{
<access-modifier> [static] <return type> Method name (<signature>);
<access-modifier> [static] <variable type> Variable name;}
Example: class Box {
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Creating an Object
• Object help you to access the members of a class(fields, methods and properties) by using dot (.)
operator
• Object is created with new keyword
Syntax: <class name> <object name> = new <class name>();
class Car
{
string color = "red";
static void Main(string[] args)
{ Car myObj = new Car();
Console.WriteLine(myObj.color);
}}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Using this keyword
• this keyword refers to the current instance of a class
• this keyword cannot be used with static members because static members accessed by a class not
by the instances of a class
public class Employee
{
private string alias;
private string name;
public Employee(string name, string alias)
{
// Use this to qualify the members of the class
// instead of the constructor parameters.
this.name = name;
this.alias = alias;
}}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Creating an Array Object
• Array of object is different from object of C++ and Java
static public void Main()
{
// Creating and initializing
// object array
object[] arr = new object[6];
arr[0] = 3.899;
arr[1] = 3;
arr[2] = 'g';
arr[3] = "Geeks";
}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Using the Nested Classes
• Class within the other class is nested class
class Outer_class {
// Code.. Syntax
class Inner_class {
// Code.. }}
public class Outer_class {
// Method of outer class
public void method1()
{ Console.WriteLine("Outer class method"); }
// Inner class
public class Inner_class {
// Method of inner class
public void method2() {
Console.WriteLine("Inner class Method"); } }}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Defining Partial classes and Methods
• In C#, you can split the implementation of a class, a struct, a method, or an interface in
multiple .cs files using the partial keyword.
• The compiler will combine all the implementation from multiple .cs files when the program is
compiled.
public partial class Employee
{
public int EmpId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Using method as class members
<access specifier> class class_name {
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list) {
// method body
}<access specifier> <return type> method2(parameter_list) {
// method body
}
...
<access specifier> <return type> methodN(parameter_list) {// method body }}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Passing an Object as an Argument to a Method
public void AddOb(Sample S1, Sample S2)
{
//adding the value of S1 and S2,
//assigning sum in value of current object
value = S1.value + S2.value;
}}
class Program
{static void Main()
{//objects creation
Sample S1 = new Sample();
Sample S2 = new Sample();
}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Returning value from method
class ReturnTest
{ static double CalculateArea(int r)
{
double area = r * r * Math.PI;
return area; }
static void Main()
{
int radius = 5;
double result = CalculateArea(radius);
Console.WriteLine("The area is {0:0.00}", result);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();}}
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Describing the access modifiers
• Public Modifier: Allows public access to members both inside and outside a class without any
restrictions
• Internal Modifier: allow internal access to members. Only the current assembly can access these
members
• Protected Modifier: Allow protected access members. You can access protected members from
either the class in which they are declared or a class derived from the class in which they are
declared
• Private Modifier: The internal access modifiers can access within the program that contain its
declarations
• Protected internal modifier:

04/04/2024 11
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Properties
class Person
{
private string name; // field

public string Name // property


{
get { return name; } // get method
set { name = value; } // set method
}
}

04/04/2024 12
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
• Indexers
This is a new concept introduced by C#
An indexer allows an instance of a class or struct to be indexed as an array.
// Indexer declaration
Syntax:
<access_modifier> return_type this [argument_list]
{get
In the above syntax:
{
// get block code access_modifier: It can be public, private, protected or
} internal.
return_type: It can be any valid C# type.
set this: It is the keyword which points to the object of the
{ current class.
// set block code argument_list: This specifies the parameter list of the
indexer.
}} get{ } and set { }: These are the accessors.
private string[] val = new string[3]; //Example
04/04/2024 13
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
• Struct
Access_Modifier struct structure_name //Syntex
{
// Fields
// Parameterized constructor
// Constants
// Properties
// Indexers
// Events
// Methods etc.
}

04/04/2024 14
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Encapsulation
• Encapsulation is a process of hiding the irrelevant data and showing only the relevant information
of a specific object to a user
• In terms of opps encapsulation is a process of wrapping up of data and member of a class
• Provides a way to protect unauthorized access

04/04/2024 15
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Inheritance
• Most important in C#, promotes for reusability of code and eliminates the redundant code
• Inheritance is property through which a class derives properties from other class
• A parents class at a higher level I the class hierarchy
<acess-specifier> class <base_class> {
..}
class <derived_class> : <base_class> {
...}
• Inheritance is of 4 types
• Single inheritance
• Hierarchical inheritance
• Multi level inheritance
• Multiple inheritance

04/04/2024 16
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Inheritance
• Most important in C#, promotes for reusability of code and eliminates the redundant code
• Inheritance is property through which a class derives properties from other class
• A parents class at a higher level I the class hierarchy
<acess-specifier> class <base_class> {
..}
class <derived_class> : <base_class> {
...}
• Inheritance is of 4 types
• Single inheritance
• Hierarchical inheritance
• Multi level inheritance
• Multiple inheritance

04/04/2024 17
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Constructor
• Constructor is a special method of a class
• A constructor is called by default whenever an object of a class is created
• All the derived classes have their default constructor
• The default constructor of a base class is called automatically and then the derived class
constructor is called
Sealed class
• A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated.
• The design intent of a sealed class is to indicate that the class is specialized and there is no need
to extend it to provide any additional functionality through inheritance to override its behavior.

04/04/2024 18
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Extension Method
• Extension method is a method that helps you to extend a class without creating a new derived
class or modifying the original class
• Allows you to add new methods in the existing class or in the structure without modifying the
source code of the original type and you do not require any kind of special permission from the
original
public static class Demo
{ public static int myExtensionMethod(this string str)
{ return Int32.Parse(str);} }
class Program{
static void Main(string[] args)
{string str1 = "565";
int n = str1.myExtensionMethod();
Console.WriteLine("Result: {0}", n);
04/04/2024Console.ReadLine();} 19
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Polymorphism
• This is one of the important feature of OOPs
• That is used to exhibit different forms of a particular procedure
• Allows you to invoke methods of a derived class through base class reference during runtime
• Provides different implementation of methods in a class that are called through the same name
• There are 2 types of polymorphism
1. Static polymorphism/ compile time polymorphism/ overloading
2. Dynamic polymorphism/ run time polymorphism/ overriding

04/04/2024 20
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}}
class Pig : Animal // Derived class (child)
{ public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}}
class Dog : Animal // Derived class (child)
{ public void animalSound()
{ Console.WriteLine("The dog says: bow wow");
}}
04/04/2024 21
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Static polymorphism/ compile time polymorphism/
overloading
• 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
public class Calculate
{
public void Add Numbers (int a, int b)
{
Console.WriteLine("a + b = {0}", a + b);
}
public void Add Numbers(int a, int b, int c)
{
Console.WriteLine("a + b + c = {0}", a + b + c);
}
}
04/04/2024 22
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Dynamic polymorphism/ run time polymorphism/
overriding
• C# allows you to create abstract classes that are used to provide partial class implementation of
an interface. Implementation is completed when a derived class inherits from it
• Dynamic polymorphism also referred to as run-time or late binding polymorphism because of the
decision about which method is to be called is made at run time.
• In dynamic polymorphism, we override the base class method in derived class using inheritance,
and this can be achieved using override and virtual keywords.
• Virtual keyword is used for generating a virtual path for its derived classes on implementing
method overriding. Virtual keyword is used within a set with override keyword. It is used as:
// Base Class
class A
{
public virtual void show()
{ Console.WriteLine("Hello: Base Class!");
Console.ReadLine(); }}
04/04/2024 23
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

In C# we can use 2 types of keywords for Method Overriding:

virtual keyword: This modifier or keyword use within base class method. It is used to modify a method in
base class for overridden that particular method in the derived class.
override: This modifier or keyword use with derived class method. It is used to modify a virtual or abstract
method into derived class which presents in base class.
04/04/2024 24
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Override Keyword-Override keyword is used in the derived class of the base class in order to
override the base class method. Override keyword is used with virtual keyword, as:
class A // Base Class
{
public virtual void show()
{
Console.WriteLine("Hello: Base Class!");
Console.ReadLine();
}
}
class B : A // Derived Class
{ public override void show()
{ Console.WriteLine("Hello: Derived Class!");
Console.ReadLine();
}
}
04/04/2024 25
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Abstraction
• Abstraction is the process of hiding the details of a particular concept or object
Abstract classes
Abstract class can not be instantiated
abstract class Base class
{
//Data member and member function
}
Class Derived class: BaseClass
{//Data member and member function}
Class MainClass()
{Base class bc; // cant be instantiated
Derived class dc; // can be instantiated

04/04/2024 26
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Characteristics of abstract class
• Restricts instantiation implying that you cannot create on object of an abstract class
• Allows you to define abstract as well as non-abstract members in it
• Requires at least one abstract method in it
• Restricts the use sealed keyword in it
• Possesses public access specifier; therefore it can be used any where in a program
Abstract Method
• An abstract method is similar to virtual method which does not provide any implementation
Public abstract void area (int Length, int breadth)
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{ Console.WriteLine("Zzz");}}
04/04/2024 27
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Interfaces
• Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have method body and cannot be
instantiated.
• It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve
fully abstraction because it cannot have method body.
• Interfaces
Syntax for Interface Declaration:
interface <interface_name >
{
// declare Events
// declare indexers
// declare methods
// declare properties
}
04/04/2024 28
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Inheritance in interfaces
• C# allows the user to inherit one interface into another interface. When a class implements the
inherited interface then it must provide the implementation of all the members that are defined
within the interface inheritance chain.
• Inheritance
Syntax:
// declaring an interface
access_modifier interface interface_name
{
// Your code
}
// inheriting the interface
access_modifier interface interface_name : interface_name
{
// Your code
}
04/04/2024 29

You might also like