Lecture 2 - C# Class - Method
Lecture 2 - C# Class - Method
Content
Explain classes and objects
Define and describe methods
List the access modifiers
Explain method overloading
Define and describe constructors and destructors
Object-Oriented Programming
Programming languages are based on two fundamental concepts, data and
ways to manipulate data.
Traditional languages such as Pascal and C used the procedural approach
which focused more on ways to manipulate data rather than on the data itself.
This approach had several drawbacks such as lack of re-use and lack of
maintainability.
To overcome these difficulties, OOP was introduced, which focused on data
rather than the ways to manipulate data.
The object-oriented approach defines objects as entities having a defined set
of values and a defined set of operations that can be performed on these
values.
Features
Object-oriented programming provides the following features:
• Abstraction is the feature of extracting only the required information from
Abstraction objects. For example, consider a television as an object. It has a manual stating
how to use the television. However, this manual does not show all the technical
details of the television, thus, giving only an abstraction to the user.
• Details of what a class contains need not be visible to other classes and objects
Encapsulation that use it. Instead, only specific information can be made visible and the others
can be hidden. This is achieved through encapsulation, also called data hiding.
Both abstraction and encapsulation are complementary to each other.
• Inheritance is the process of creating a new class based on the attributes and
methods of an existing class. The existing class is called the base class whereas the
Inheritance new class created is called the derived class. This is a very important concept of
object-oriented programming as it helps to reuse the inherited attributes and
methods.
An object stores its identity and state in fields (also called variables)
and exposes its behavior through methods.
Class
Several objects have a common state and behavior and thus, can be
grouped under a single class.
Example
Creating Classes
The concept of classes in the real world can be extended to the programming world,
similar to the concept of objects.
In object-oriented programming languages like C#, a class is a template or blueprint
which defines the state and behavior of all objects belonging to that class.
A class comprises fields, properties, methods, and so on, collectively called data
members of the class. In C#, the class declaration starts with the class keyword
followed by the name of the class.
The following syntax is used to declare a class:
public class ClassName
{
// class member
}
Creating Classes - example
Guidelines for Naming Classes
There are certain conventions to be followed for class names while
creating a class that help you to follow a standard for naming classes.
These conventions state that a class name:
Should be a noun and written in initial caps, and not in
mixed case.
Cannot be a C# keyword.
Cannot begin with a digit but can begin with the ‘@’
character or an underscore (_).
Example:
Valid class names are: Account, @Account, and _Account.
Invalid class names are: 2account, class, Acccount, and Account123.
Instantiating Objects
It is necessary to create an object of the class to access the variables and
methods defined within it.
In C#, an object is instantiated using the new keyword. On
encountering the new keyword, the Just-in-Time (JIT) compiler
allocates memory for the object and returns a reference of that allocated
memory.
The following syntax is used to instantiate an object.
Syntax:
<ClassName> <objectName> = new <ClassName>();
Example
Methods
Methods are functions declared in a class and may be used to perform operations on
class variables.
They are blocks of code that can take parameters and may or may not return a value.
A method implements the behavior of an object, which can be accessed by
instantiating the object of the class in which it is defined and then invoking the
method.
Methods specify the manner in which a particular operation is to be carried out on
the required data members of the class.
Example:
The class Car can have a method Brake()that represents the ’Apply Brake’ action.
To perform the action, the method Brake()will have to be invoked by an object of class
Car.
Creating Methods
Conventions to be followed for naming methods state that a method name:
Syntax:
<access_modifier> <return_type> <MethodName> ([ list of parameters])
{
// body of method
}
Example
The following code shows the definition of a method named Add() that
adds two integer numbers:
using System;
class Sum
{
int Add(int numOne, int numTwo)
{
int addResult = numOne + numTwo;
Console.WriteLine(“Addition = “ + addResult);
. . .
}
}
Invoking Methods
A method can be invoked in a class by creating
an object of the class where the object name is
followed by a period (.) and the name of the
method followed by parentheses.
In C#, a method is always invoked from another
method. This is referred to as the calling method
and the invoked method is referred to as the
called method.
The following figure displays how a method
invocation or call is stored in the stack in
memory and how a method body is defined:
Example
class Book{
string _bookName;
public string Print() {
return _bookName;
}
public void Input(string bkName) {
_bookName = bkName;
}
static void Main(string[] args)
{
Book objBook = new Book();
objBook.Input(“C#-The Complete Reference”);
Console.WriteLine(objBook.Print());
}
}
Method Parameters and Arguments
Method parameters and arguments:
• The variables included in a method definition are
called parameters. Which may have zero or more
parameters, enclosed in parentheses and separated
Parameters by commas. If the method takes no parameters, it is
indicated by empty parentheses.
• When the method is called, the data that you send into
Arguments the method's parameters are called arguments.
Example
public class Rectangle {
double _length;
double _breadth;
public Rectangle() {
_length = 13.5;
_breadth = 20.5;
}
public Rectangle(double len, double wide) {
_length = len;
_breadth = wide;
}
public double Area() {
return _length * _breadth;
}
static void Main(string[] args) {
Rectangle objRect1 = new Rectangle();
Console.WriteLine(“Area of rectangle = “ + objRect1.Area());
Rectangle objRect2 = new Rectangle(2.5, 6.9);
Console.WriteLine(“Area of rectangle = “ + objRect2.Area());
}
}
Destructors
A destructor is a special method which has the same name as the class
but starts with the character ~ before the class name and immediately
de-allocate memory of objects that are no longer required. Following
are the features of destructors:
Destructors cannot be overloaded or inherited.
Destructors cannot be explicitly invoked.
Destructors cannot specify access modifiers and cannot take parameters.
Example
class Employee {
string name;
public Employee() {}
public Employee(string name) {
this.name = name;
}
~Employee() {
Console.WriteLine(“Destructor runs.”);
}
}