Basic OOP

Md Tareq Shah Alam
11 min readApr 27, 2024

--

OOP

Thanks to W3Schools.

I have collected this article for my personal job preparation. I didn’t write this article rather I have collected information ragarding OOP. If you want then you can learn from the website above I have mensioned or read from here. Both are same. The difference is, this article is my practice. I have revised one more time the OOP concept from that website and then written by myself here. I have skipped some topics which is not important for.

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the C# code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Class/Object

A Class is blueprint for creating objects. Imagine a class into your institution. There the class is the combination of all the element regarding that class. All the element means all the students.

Create a Class

To create a class, use the class keyword:

class Car 
{
string color = "red";
}

Create an Object

An object is created from a class. We have already created the class named Car, so now we can use this to create objects.

To create an object of Car, specify the class name, followed by the object name, and use the keyword new:

class Car 
{
string color = "red";

static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}

Multiple Objects

You can create multiple objects of one class:

class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj1 = new Car();
Car myObj2 = new Car();
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}

Using Multiple Classes

You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the fields and methods, while the other class holds the Main() method (code to be executed)).

Class Members

Fields and methods inside classes are often referred to as “Class Members”:

Create a Car class with three class members: two fields and one method.

// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}

Fields

In the previous chapter, you learned that variables inside a class are called fields, and that you can access them by creating an object of the class, and by using the dot syntax (.).

The following example will create an object of the Car class, with the name myObj. Then we print the value of the fields color and maxSpeed:

class Car 
{
string color = "red";
int maxSpeed = 200;

static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}

Object Methods

You learned from the C# Methods chapter that methods are used to perform certain actions.

Methods normally belong to a class, and they define how an object of a class behaves.

Just like with fields, you can access methods with the dot syntax. However, note that the method must be public. And remember that we use the name of the method followed by two parentheses () and a semicolon ; to call (execute) the method:

class Car 
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}

static void Main(string[] args)
{
Car myObj = new Car();
myObj.fullThrottle(); // Call the method
}
}

Constructors

A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when an object of a class is created. It can be used to set initial values for fields:

// Create a Car class
class Car
{
public string model; // Create a field

// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}

static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}

// Outputs "Mustang"

Constructor Parameters

Constructors can also take parameters, which is used to initialize fields.

The following example adds a string modelName parameter to the constructor. Inside the constructor we set model to modelName (model=modelName). When we call the constructor, we pass a parameter to the constructor ("Mustang"), which will set the value of model to "Mustang":

class Car
{
public string model;

// Create a class constructor with a parameter
public Car(string modelName)
{
model = modelName;
}

static void Main(string[] args)
{
Car Ford = new Car("Mustang");
Console.WriteLine(Ford.model);
}
}

// Outputs "Mustang"

Access Modifiers

By now, you are quite familiar with the public keyword that appears in many of our examples:

public string color;

The public keyword is an access modifier, which is used to set the access level/visibility for classes, fields, methods and properties.

C# has the following access modifiers:

img

There’s also two combinations: protected internal and private protected.

For now, lets focus on public and private modifiers.

Private Modifier

If you declare a field with a private access modifier, it can only be accessed within the same class:

class Car
{
private string model = "Mustang";

static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

Public Modifier

If you declare a field with a public access modifier, it is accessible for all classes:

class Car
{
public string model = "Mustang";
}

class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}

Properties and Encapsulation

The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:

  • declare fields/variables as private
  • provide public get and set methods, through properties, to access and update the value of a private field

Properties

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, sometimes we need to access them - and it can be done with properties.

A property is like a combination of a variable and a method, and it has two methods: a get and a set method:

class Person
{
private string name; // field

public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}

Example explained

The Name property is associated with the name field. It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter.

The get method returns the value of the variable name.

The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.

Now we can use the Name property to access and update the private field of the Person class:

class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}

class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}

Why Encapsulation?

  • Better control of class members (reduce the possibility of yourself (or others) to mess up the code)
  • Fields can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • Flexible: the programmer can change one part of the code without affecting other parts
  • Increased security of data

Inheritance

In C#, it is possible to inherit fields and methods from one class to another. We group the “inheritance concept” into two categories:

  • Derived Class (child) — the class that inherits from another class
  • Base Class (parent) — the class being inherited from

To inherit from a class, use the : symbol.

In the example below, the Car class (child) inherits the fields and methods from the Vehicle class (parent):

class Vehicle  // base class (parent) 
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}

class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
}

class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();

// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}

Polymorphism

Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit fields and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

For example, think of a base class called Animal that has a method called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

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");
}
}

Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is used for classes and methods:

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).

An abstract class can have both abstract and regular methods:

abstract class Animal 
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}

Interface

Another way to achieve abstraction in C#, is with interfaces. An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies):

// interface
interface Animal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be “implemented” (kinda like inherited) by another class. To implement an interface, use the : symbol (just like with inheritance). The body of the interface method is provided by the "implement" class. Note that you do not have to use the override keyword when implementing an interface:

// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}

// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}

Notes on Interfaces:

  • Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an “IAnimal” object in the Program class)
  • Interface methods do not have a body — the body is provided by the “implement” class
  • On implementation of an interface, you must override all of its methods
  • Interfaces can contain properties and methods, but not fields/variables
  • Interface members are by default abstract and public
  • An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

1) To achieve security — hide certain details and only show the important details of an object (interface).

2) C# does not support “multiple inheritance” (a class can only inherit from one base class). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).

Enum

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with a comma:

enum Level 
{
Low,
Medium,
High
}

You can access enum items with the dot syntax:

Level myVar = Level.Medium;
Console.WriteLine(myVar);

Enum inside a Class

You can also have an enum inside a class:

class Program
{
enum Level
{
Low,
Medium,
High
}
static void Main(string[] args)
{
Level myVar = Level.Medium;
Console.WriteLine(myVar);
}
}

Files

Working With Files

The File class from the System.IO namespace, allows us to work with files:

using System.IO;  // include the System.IO namespace

File.SomeFileMethod(); // use the file class with methods

The File class has many useful methods for creating and getting information about files. For example:

img

Exceptions — Try..Catch

When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).

C# try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

try 
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors

If an error occurs, we can use try...catch to catch the error and execute some code to handle it.

In the following example, we use the variable inside the catch block (e) together with the built-in Message property, which outputs a message that describes the exception:

try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception class. There are many exception classes available in C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, etc:

static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}

static void Main(string[] args)
{
checkAge(15);
}

The

End

--

--