0% found this document useful (0 votes)
15 views12 pages

Oops

The document provides an in-depth overview of object-oriented programming concepts in .NET, focusing on inheritance, encapsulation, polymorphism, and abstraction. It explains key features such as the use of the 'base' keyword, constructors, access modifiers, virtual methods, and the differences between overriding and hiding methods. Additionally, it discusses the importance of interfaces and abstract classes in achieving abstraction and encapsulation in programming.

Uploaded by

Varun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views12 pages

Oops

The document provides an in-depth overview of object-oriented programming concepts in .NET, focusing on inheritance, encapsulation, polymorphism, and abstraction. It explains key features such as the use of the 'base' keyword, constructors, access modifiers, virtual methods, and the differences between overriding and hiding methods. Additionally, it discusses the importance of interfaces and abstract classes in achieving abstraction and encapsulation in programming.

Uploaded by

Varun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

OOPS

Inheritance
It allows a class to "inherit" (behavior or characteristics) of another, more general class.
In .NET and other modern programming languages, a class can inherit from a single class
only (single inheritance), unlike C++ which supports inheriting from multiple classes
(multiple inheritance). This limitation is necessitated by the difficulty in deciding which
method to use when there are duplicate methods across classes (in C++, this problem is
solved in a very complicated manner). In .NET, classes can inherit multiple interfaces.

Base keyword
The base keyword is used to access members of the base class from within a derived class. Use
it if you want to:

Call a method on the base class that has been overridden by another method.
Specify which base-class constructor should be called when creating instances of the
derived class.

Constructors with Inheritance

When inheriting a class, our constructors must call the base class constructor, so that it can
initialize its member variables. If we do not do this explicitly, the compiler will place a call to the
parameterless base class constructor, ":base()", at the beginning of all our inheriting class'
constructors.

public class ExtendingClass : BaseClass


{
public ExtendingClass() { … }
}
//This actually looks like this (spot the differences):
public class ExtendingClass : BaseClass
{
public ExtendingClass() : base() { … }
}

If the base class has no default constructor (one without parameters) or that constructor is
hidden (Either class is static, or has private constructor, or has explicitly defined constructor),
our constructors need to explicitly call one of the other base class constructors. The omission of
such a call will result in a compile-time error.
public class Felidae
{
private bool male;
// This constructor calls another constructor
public Felidae() : this(true)
{}
// This is the constructor that is inherited
public Felidae(bool male)
{
this.male = male;
}
public bool Male
{
get { return male; }
set { this.male = value; }
}
}

public class Lion : Felidae


{
private int weight;
// This will call constructor of base class
public Lion(bool male, int weight) : base(male)
{
this.weight = weight;
}
public int Weight
{
get { return weight; }
set { this.weight = value; }
}
}

Method with Inheritance

public class Person


{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";

public virtual void GetInfo()


{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee : Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}

class TestClass
{
static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
/*
Output
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
*/

this Keyword
The current instance of the class
Uses

To qualify members hidden by similar names, for example:

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

To pass an object as a parameter to other methods,


CalcTax(this);

To declare indexers

public int this[int param]


{
get { return array[param]; }
set { array[param] = value; }
}

Access Modifiers of Class Members and Inheritance


Protected defines class members which are not visible to users of the class (those who
initialize and use it), but are visible to all inheriting classes (descendants).
Chapter 20. Object-Oriented Programming Principles 813
Protected Internal defines class members which are both internal, i.e. visible within the
entire assembly, and protected, i.e. not visible outside the assembly, but visible to classes
who inherit it (even outside the assembly).
When a base class is inherited:
All of its public, protected and protected internal members (methods, properties, etc.) are
visible to the inheriting class.
All of its private methods, properties and member-variables are not visible to the inheriting
class.
All of its internal members are visible to the inheriting class, only if the base class and the
inheriting class are in the same assembly

System.Object Class
In .NET every class, which does not inherit a class explicitly, inherits the system class
System.Object by default.
Every class, which inherits from another class indirectly, inherits Object from it.
Because of this property, every class instance can be cast to Object.

Upcasting

Convert class object to system.object


Downcasting

converting system.object to class object

Object.ToString()

It returns a textual representation of an object. Every object includes this method and
therefore has a textual representation

public class AfricanLion : Lion


{
// …
public override string ToString()
{
return string.Format("(AfricanLion, male: {0}, weight: {1})",
this.Male, this.Weight);
}
// …
}

Virtual Method in Inhertiance

override

Methods inherited from the base class and declared as virtual can be overridden. This means
changing their implementation; the original source code from the base class is ignored and new
code takes its place. Like overriding ToString method above.
This indicates for the compiler to use the last defined implementation of a method. Even if the
method is called on a reference to the base class it will use the implementation overriding it.

public class Base


{
public virtual void DoIt()
{
}
}

public class Derived : Base


{
public override void DoIt()
{
}
}

Base b = new Derived();


b.DoIt();
// Calls Derived.DoIt

New
when we use the keyword new, we create a new method, which hides the old one. The old
method can then only be called with an upcast.
The new modifier instructs the compiler to use your child class implementation instead of the
parent class implementation. Any code that is not referencing your class but the parent class
will use the parent class implementation.

public class Base


{
public virtual void DoIt()
{
}
}

public class Derived : Base


{
public new void DoIt()
{
}
}

Base b = new Derived();


Derived d = new Derived();

b.DoIt(); // Calls Base.DoIt


d.DoIt(); // Calls Derived.DoIt

Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods
which happen to have the same name, rather than the derived method overriding the base
method.

using System;
using System.Text;

namespace OverrideAndNew
{
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public void Method2()
{
Console.WriteLine("Base - Method2");
}

// This method is always called hiding child's implmentation


public void Method3()
{
Console.WriteLine("Base - Method3");
}
}

class DerivedClass : BaseClass


{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
public void Method3()
{
Console.WriteLine("Base - Method3");
}
}
class Program
{
static void Main(string[] args)
{
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
BaseClass bc = new BaseClass();
bc.Method1();
bc.Method2();
bc.Method3();
//Base - Method1
//Base - Method2
//Base - Method3

// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
DerivedClass dc = new DerivedClass();
dc.Method1();
dc.Method2();
dc.Method3();
//Derived - Method1
//Derived - Method2
//Base - Method3

// The following two calls produce different results, depending


// on whether override (Method1) or new (Method2) is used.
BaseClass bcdc = new DerivedClass();
bcdc.Method1();
bcdc.Method2();
bcdc.Method3();
//Derived - Method1 //override
//Base - Method2 // new
//Base - Method3

// Error
//DerivedClass dcbc = new BaseClass();
}
}
}

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-
structs/knowing-when-to-use-override-and-new-keywords

Transitive Properties of Inheritance


Let’s take the indicator "larger than" (>) as an example. If A>B and B>C, we can conclude that
A>C. This means that the relation "larger than" (>) is transitive, because we can unequivocally
determine whether A is larger or smaller than C and vice versa.
If the class Lion inherits the class Felidae and the class AfricanLion inherits Lion, then this implies
that AfricanLion inherits Felidae. Therefore, AfricanLion also has the property Male, which is
defined in Felidae. This useful property allows a particular functionality to be defined in the
most appropriate class.

Abstraction
Working with something we know how to use without knowing how it works internally. Like
using List, We do not care internally if List uses Array or linked List or Tree, we just use List for
our collection.

Interfaces
An interface can only declare methods and constants.

public interface Reproducible<T> where T : Felidae


{
T[] Reproduce(T mate);
}
public class Lion : Felidae, Reproducible<Lion>
{
// …
Lion[] Reproducible<Lion>.Reproduce(Lion mate)
{
return new Lion[]{new Lion(true, 12), new Lion(false, 10)};
}
}

The best way to achieve abstraction is by working though interfaces. A component works with
interfaces which another implements. That way, a change in the second component will not
affect the first one as long as the new component implements the old interface.
Some important interfaces from the Common Type System (CTS) are the list and collection
interfaces: System.Collections.Generic.IList and System.Collections.Generic.ICollection.
When Should we Use Interface: The answer to this question is: always when we want to achieve
abstraction of data or actions, whose implementation can change later on. Code, which
communicates with another piece of code through interfaces, is much more resilient to changes

Encapsulation
"information hiding"
Like using access modifier, doesn’t publicly disclose information about its inner workings

Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. Now,

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.

Two Important property of Encapsulation

Data Protection: Encapsulation protects the internal state of an object by keeping its data
members private. Access to and modification of these data members is restricted to the class’s
public methods, ensuring controlled and secure data manipulation.
Information Hiding: Encapsulation hides the internal implementation details of a class from
external code. Only the public interface of the class is accessible, providing abstraction and
simplifying the usage of the class while allowing the internal implementation to be modified
without impacting external code.

Polymorphism
Polymorphism allows treating objects of a derived class as objects of its base class
For example, big cats (base class) catch their prey (a method) in different ways. A Lion (derived
class) sneaks on it, while a Cheetah (another derived class) simply outruns it.

Abstract Classes
The class in incomplete and the class is not ready to be instantiated.
Class with at least one abstract method must be abstract, however, it is also possible to
define a - class as an abstract one, even when there are no abstract methods in it.
Abstract classes, as well as interfaces, cannot be instantiated

public abstract class Animal


{
public void PrintInformation()
{
// Note the usage of this keyword
Console.WriteLine("I am a {0}.", this.GetType().Name);
Console.WriteLine(GetTypicalSound());
}
protected abstract String GetTypicalSound();
}

public class Cat : Animal


{
protected override String GetTypicalSound()
{
return "Meoooow!";
}
}
public class AbstractClassExample
{
static void Main()
{
Animal cat = new Cat();
cat.PrintInformation();
//I am a Cat.
//Meoooow!
}
}

Purely Abstract Classes

A pure abstract class is an abstract class, which has no implemented methods and no member
variables. It is very similar to an interface. The fundamental difference is that a class can
implement many interfaces and inherit only one class (even if that class is abstract).

Virtual Method in Polymorphism


A method, which can be overridden in a derived class, is called a virtual method. Rewriting
of methods is also called overriding of virtual methods.
Virtual methods as well as abstract methods can be overridden. Abstract methods are
actually virtual methods without a specific implementation.

public abstract class Felidae


{
public abstract bool CatchPrey(object prey);
}

public interface Reproducible<T> where T : Felidae


{
T[] Reproduce(T mate);
}

public class Lion : Felidae, Reproducible<Lion>


{
public override void CatchPrey(object prey)
{
Console.WriteLine("Lion.CatchPrey");
}

Lion[] Reproducible<Lion>.Reproduce(Lion mate)


{
return new Lion[]{new Lion(true, 12), new Lion(false, 10)};
}
}

public class AfricanLion : Lion


{
public override void CatchPrey(object prey)
{
Console.WriteLine("AfricanLion.CatchPrey");
}
}
public class VirtualMethodsExample
{
static void Main()
{
Lion lion = new Lion(true, 80);
lion.CatchPrey(null);
// Will print "Lion.CatchPrey"

AfricanLion lion = new AfricanLion(true, 120);


lion.CatchPrey(null);
// Will print "AfricanLion.CatchPrey"

Lion lion = new AfricanLion(false, 60);


lion.CatchPrey(null);
// Will print "AfricanLion.CatchPrey", because
// the variable lion has a value of type AfricanLion
// the implementation of the base class is hidden and omitted.
}
}

In case we want to complement the old implementation rather than override it

public class IndiaLion : Lion


{
public override void CatchPrey(object prey)
{
Console.WriteLine("AfricanLion.CatchPrey");
Console.WriteLine("calling base.CatchPrey");
Console.Write("\t");
base.CatchPrey(prey);
Console.WriteLine("...end of call.");
}
}
//Output: Lion lion = new IndiaLion(false, 60);
//AfricanLion.CatchPrey
//calling base.CatchPrey
//Lion.CatchPrey
//...end of call.

Sealed Method & Class


Marking any method or class as sealed can prevent it from getting inherited.

public sealed override string GetTypicalSound()


{
return "Roar!";
}

You might also like