Info
This article is a verbal explanation op OOP with some terms that might only apply to the C# OOP, but most of it will be general OOP
As the name suggests, Object-Oriented-Programming refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
Theory
in this section we will look at the theory behind it etc, Specific things like, “how does a constructor work” can be found under Specifics.
Class Theory
A class is a datatype that is defined by the programmer of the application. It consists of data and functions which can be used and accessed by creating an instance of the class. A class is kind of like a blueprint.
Example
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are their properties.
Example from Geeksforgeeks.
Object Theory
Objects represent the real entities. An object is an instance of a class. When a class is defined, no memory is allocated but when it is instantiated (an object is created) memory is allocated. An object has an identity, state, and behaviour. Each object contains data and code to manipulate the data. Multiple objects can interact with each other, they don’t need to know everything about the object they interact with, they just need to know the method they want to use or the property / field they want to access. So looking back on the “A class is kind of like a blueprint.”, an object is the house built from the blueprint we have. and we can make “infinite1” houses from the same blueprint.
Data Abstraction
Data abstraction is one of the most essential and important features of object-oriented programming. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. Think for example about a car, the driver knows that when he presses the brakes that it will stop the car, but he doesn’t know the inner mechanism of the car nor the implementation of the brakes. In programming you can do this by using Access modifiers.
Encapsulation
Encapsulation is defined as the wrapping up of data under a single unit, it is the full mechanism that binds together the code and the data. 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 their 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.
Example
Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section, etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”.
Example from Geeksforgeeks.
Inheritance
Inheritance is the capability of a class to derive properties and characteristics from another class. So when we create a class, we do not need to write all the properties and functions again and again, as these can be inherited from another class that possesses it. Inheritance allows the user to reuse the code.
Example
I have this class called
Animal
, which has the method for breathing, Then I create another class calledDog
that inherits from theAnimal
class, this makes it so that it also has the breathing method, but when I give theDog
class a Bark method, myAnimal
class wont get the Bark method since Inheritance is a 1 way street.
Polymorphism
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. For example, A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. This is called polymorphism.
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at runtime. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run time. Dynamic Method Binding One of the main advantages of inheritance is that some derived class D has all the members of its base class B. Once D is not hiding any of the public members of B, then an object of D can represent B in any context where a B could be used. This feature is known as subtype polymorphism.
Message Passing
It is a form of communication used in object-oriented programming as well as parallel programming. Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function, and the information to be sent.
Specifics
This section is more of a showcase of everything OOP adds whereas the above part is more of a vague description to it all. I am again going to cut it in sections for everything. It will sometimes contain [[C-Sharp|C#]] examples. Some things differ between languages, so this article is specifically a look at C#.
Class
A class is a datatype that is defined by the programmer of the application. It consists of data and functions which can be used and accessed by creating an instance of the class. A class is kind of like a blueprint.
class Person
{
public string Name;
public int Id;
}
Properties
A property is a variable that is contained by a class / object.
Object
Objects represent the real entities. An object is an instance of a class. So looking back on the “A class is kind of like a blueprint.”, an object is the house built from the blueprint we have. and we can make “infinite1” houses from the same blueprint. Below is an example on how to create an Object:
Person ruud = new Person();
Person pascal = new Person();
Person johan = new Person();
Person jessica = new Person();
jessica.Name = "Jessica"
Required fields
Sometimes you want to make sure your class has the fields assigned on creation, you do this in the constructor.
class Person
{
public string Name;
public int Id;
public Person(string name, int id)
{
this.Name = name;
this.Id = id;
}
}
Person jessica = new Person("Jessica", 42);
It is possible to have multiple constructors, when they have the same arguments it will overwrite the other, but when the constructors have different arguments you can choose which to choose on creation of the object. This is also called Constructor Overloading. You can do the same thing with methods.
Methods
A method is a Function that is owned by a class / object2. These Methods have access to the class / object it is contained by. This means that you can create methods to change the name of your person:
class Person
{
private string Name;
public void NameChange(string name) {
this.Name = name;
}
}
Person ruud = new Person();
ruud.NameChange("Harm");
Protection of data
To protect Methods and Properties from usage outside of the object, we use Access Modifiers like public
and private
to indicate whether only the object itself can use it, or whether everything can.
Fields
When you make a property private it is a field.
Nesting
When you set a Class as a field / property, it is called nesting. This means that 1 Object will contain another Object. This is also named Composition.
class Person
{
private Person Parent;
public void SetParent(Person parent) {
this.Parent = parent;
}
}
Person jessica = new Person();
Person ruud = new Person();
ruud.SetParent(jessica);
Class diagram
When you create a program with OOP it is smart to create a class diagram. This will make you find flaws beforehand, plan correctly and make it easy to continue developing when it has been a while.
Null
You can set anything as programming null, so be carefull to have validations in your code. the following code will produce a NullReferenceException
:
Person person = null;
Person person2;
Console.WriteLine(person);
Console.WriteLine(person2);
Predefined objects
Things like String and Int are also Classes, but these are built into your programming language by default.
ToString
Every class has a .ToString()
method by default in [[C-Sharp|C#]]. This converts your complex class into a string. When you do this with your own class it will return the name of your class.
class Auto {}
Auto mijnAuto = new Auto();
Console.WriteLine(mijnAuto.ToString()); // gives something like "Namespace.Auto"
You can override this functionality by using an override as seen below:
class Auto
{
public string Merk { get; set; }
public string Model { get; set; }
public override string ToString()
{
return $"Merk: {Merk}, Model: {Model}";
}
}
Auto mijnAuto = new Auto { Merk = "Tesla", Model = "Model 3" };
Console.WriteLine(mijnAuto.ToString()); // Gives "Merk: Tesla, Model: Model 3"
constructorless initialisation
you can set the value of your classes properties by doing the following:
class Person
{
public string FirstName { get; set; }
}
Person person = new Person()
{
FirstName = "Johan"
};
Inheriting Classes
Inheritance is the capability of a class to derive properties and characteristics from another class.
class Person
{
public string FirstName { get; set; }
}
class Child: Person
{
public string SchoolName { get; set; }
}
In this example above I inherit the Person class into the Child class, Child now still counts as a type of Person, but Person won’t be allowed as a type of Child.
Interfaces
Interfaces are a Datatype, this datatype is kinda like a minimalistic version of a class that tells you what methods it should have, but not the implementation of these methods. And then you inherit the interface in your class.
class INamedEntity
{
string SpeciesName()
}
class Person: INamedEntity
{
public string SpeciesName() {
return "Human";
}
}
When you don’t implement all methods of the interface your compiler will scream at you.
Static classes
In C#, if we use a static
keyword with class members, then there will be a single copy of the type member.
And, all objects of the class share a single copy instead of creating individual copies.
You can also make your variables and methods static, If a variable is declared static
, we can access the variable using the class name:
class Person
{
public static string Name = "Harm";
}
Console.WriteLine("Department: " + Person.Name);
All objects of this class will share the same name in this example.
Overloading
It is possible to have multiple constructors / methods with the same name, when they have the same arguments it will overwrite the other, but when the constructors have different arguments you can choose which to choose on creation of the object.
Constructor
class Car {
Car() {
...
}
Car(string brand) {
...
}
Car(string brand, int price) {
...
}
}
Methods
void display() { ... }
void display(int a) { ... }
float display(double a) { ... }
float display(int a, float b) { ... }
Abstract
Abstract classes can not be created into an object and have to be inherited. They do create a blueprint like an interface, but they can also have methods that already have functionality defined to them.
Sealed
Sealed classes can not be inherited by other classes. Sealed methods can not be overridden.
Explicit interface implementation
If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation. In the following example, all the calls to Paint
invoke the same method. This first sample defines the types:
public interface IControl
{
void Paint();
}
public interface ISurface
{
void Paint();
}
public class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}
Polymorphism
Polymorphism is the act of Constructor and method overloading. Or whenever you override a method.
Sources
Sources