You are on page 1of 15

OOP2

Inheritance
In C#, it is possible to inherit fields and methods from one class to another.

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):

In [ ]:
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";
}

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

myCar.honk();

Console.WriteLine(myCar.brand + " " + myCar.modelName);


}
}
// Output:- Tuut, tuut!
// Ford Mustang

Sealed keyword
If you don't want other classes to inherit from a class, use the sealed keyword. If you try to access a sealed class, C# will generate an error.

In [ ]:
sealed class Vehicle
{
...
}

class Car : Vehicle


{
...
}

// 'Car': cannot derive from sealed type 'Vehicle'

During method overriding, if we don't want an overridden method to be further overridden by another class, we can declare it as a sealed method.

In [ ]:
using System;
namespace SealedClass {

class Animal {
public virtual void makeSound() {
Console.WriteLine("Animal Sound");
}
}

class Dog : Animal {

// sealed method
sealed public override void makeSound() {

Console.WriteLine("Dog Sound");
}
}

class Puppy : Dog {


// trying to override sealed method
public override void makeSound() {
Console.WriteLine("Puppy Sound");
}
}

class Program {
static void Main (string [] args) {

// create an object of Puppy class


Puppy d1 = new Puppy();
Console.ReadLine();
}
}
}

Note: Sealing an overridden method prevents method overriding in multilevel inheritance.

Polymorphism
Polymorphism means same method name can have different functionality based on the respective class in which they are defined.

In [ ]:
class Pig
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class program
{
static void Main(string[] args)
{
Pig Sam = new Pig();
Dog Bruno = new Dog();
Sam.animalSound(); // "The pig says: wee wee"
Bruno.animalSound(); // "The dog says: bow wow"
}
}

In [ ]:
// Polymorphism in inheritance

class Animal
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal


{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal


{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class Program
{
static void Main(string[] args)
{

Animal myAnimal = new Animal();


Animal myPig = new Pig();
Animal myDog = new Dog();

myAnimal.animalSound(); //The animal makes a sound


myPig.animalSound(); //The animal makes a sound
myDog.animalSound(); //The animal makes a sound

}
}

The output from the example above was probably not what we expected. That is because the base class method overrides the derived class method,
when they share the same name.

However, C# provides an option to override the base class method, by adding the virtual keyword to the method inside the base class, and by using
the override keyword for each derived class methods.

In [ ]:
class Animal
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal


{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
base.animalSound();
}
}

class Dog : Animal


{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();

myAnimal.animalSound(); // The animal makes a sound


myPig.animalSound(); // The pig says: wee wee
myDog.animalSound(); // The dog says: bow wow
}
}

However, what if we want to call the method of the base class without creating an object from base class?

In that case, we use the base keyword to call the method of the base class from the derived class.

The base keyword is used to access members in the base class that have been overridden (or hidden) by members in the subclass. You will use base
keyword when you override a functionality but still want the overridden functionality to occur also.

You can use base keyword within instance method, constructor or instance property accessor only. You can't use it inside the static method.

In [ ]:
class Animal
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal


{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");

base.animalSound();
}
}

class Program
{
static void Main(string[] args)
{
Animal myPig = new Pig();
myPig.animalSound();

}
}

// Output
// The pig says: wee wee
// The animal makes a sound

Types and Importance of Inheritance


https://www.programiz.com/csharp-programming/inheritance#:~:text=class.-,Types%20of%20inheritance,-There%20are%20the
https://www.programiz.com/csharp-programming/inheritance#:~:text=Importance%20of%20Inheritance%20in%20C%23

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.
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 by another class). An abstract class can
have both abstract and regular methods.
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).
We can use abstract class only as a base class. This is why abstract classes cannot be sealed.

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

Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')
In [ ]:
abstract class Animal // Abstract class
{
public abstract void animalSound(); // Abstract method (does not have a body)
public void sleep() // Regular method
{
Console.WriteLine("Zzz");
}
}

class Pig : Animal // Derived class (inherit from Animal)


{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee"); // The body of animalSound() is provided here
}
}

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

// Output:-
// The pig says: wee wee
// Zzz

When a non-abstract class inherits an abstract class, it should provide an implementation of the abstract methods.

In [ ]:
abstract class Animal
{
public abstract void animalSound();
}

class Pig : Animal


{
public override void makeSound()
{
Console.WriteLine("Wee Wee");
}
}

class Program
{
static void Main (string [] args)
{
Pig myPig = new Pig();
myPig.anumalSound();
}
}

// Output
// Wee Wee

Notice, we have used override with the makeSound() method. This indicates the method is overriding the method from the base class.

Note - Unlike the C# inheritance, we cannot use virtual with the abstract methods of the base class. This is because an abstract class is implicitly
virtual.

Why And When To Use Abstract Classes and Methods?

To achieve security - hide certain details and only show the important details of an object. This helps us to manage complexity by hiding details with a
simpler, higher-level idea.

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).
By default, members of an interface are abstract and public.
We cannot use access modifiers inside an interface because all members of an interface are public by default.
Interfaces can contain properties and methods, but not fields.
It is considered good practice to start with the letter "I" at the beginning of an interface, as it makes it easier for yourself and others to remember
that it is an interface and not a class.
In [ ]:
// interface

interface IAnimal
{
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.

In [ ]:
// Interface

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

class Pig : IAnimal // Pig "implements" the IAnimal interface


{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee"); // The body of animalSound() is provided here
}
}

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

// Output:-
// The pig says: wee wee
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.
To implement multiple interfaces, separate them with a comma.

In [ ]:
interface IFirstInterface
{
void myMethod(); // interface method
}

interface ISecondInterface
{
void myOtherMethod(); // interface method
}

// Implement multiple interfaces

class DemoClass : IFirstInterface, ISecondInterface


{
public void myMethod()
{
Console.WriteLine("Some text..");
}
public void myOtherMethod()
{
Console.WriteLine("Some other text...");
}
}

class Program
{
static void Main(string[] args)
{
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

// Output:-
// Some text..
// Some other text...

We can also use the reference variable of an interface. For example,

In [ ]:
interface IAnimal
{
void animalSound();
}

class Pig : IAnimal


{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

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

// Output:-
// The pig says: wee wee

Notice, we have used the reference variable of interface IAnimal. It points to the class Pig that implements it.

Though we cannot create objects of an interface, we can still use the reference variable of the interface that points to its implemented class.

Note: We must provide the implementation of all the methods of interface inside the class that implements it.

Nested Class
Refer to this from Programmiz - https://www.programiz.com/csharp-programming/nested-class

Partial Class
Refer to this from Programmiz - https://www.programiz.com/csharp-programming/partial-class-and-methods

Enums

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


Enum is short for "enumerations", which means "specifically listed".
To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with a comma.
You can access enum items with the dot syntax.

In [2]:
enum Level
{
Low,
Medium,
High
}

Level myVar = Level.Medium;


Console.WriteLine(myVar);

Medium
You can also have an enum inside a class.

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

// Medium
By default, the first item of an enum has the value 0. The second has the value 1, and so on.

To get the integer value from an item, you must explicitly convert the item to an int

In [4]:
enum Months
{
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6
}

int myNum = (int) Months.April;


Console.WriteLine(myNum);

3
You can also assign your own enum values, and the next items will update their numbers accordingly.

In [6]:
enum Months
{
January, // 0
February, // 1
March=6, // 6
April, // 7
May, // 8
June, // 9
July // 10
}

int myNum = (int) Months.April;


Console.WriteLine(myNum);

7
Enums are often used in switch statements to check for corresponding values.
In [7]:
enum Level
{
Low,
Medium,
High
}

Level myVar = Level.Medium;


switch(myVar)
{
case Level.Low:
Console.WriteLine("Low level");
break;
case Level.Medium:
Console.WriteLine("Medium level");
break;
case Level.High:
Console.WriteLine("High level");
break;
}

Medium level
Why And When To Use Enums?

Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.

Preprocessor Directives
Refer to this from Programmiz - https://www.programiz.com/csharp-programming/preprocessor-directives

C# struct
Refer to this fromn Programmiz - https://www.programiz.com/csharp-programming/struct

You might also like