Oops Concept: OOP's Overview
Oops Concept: OOP's Overview
Oops Concept: OOP's Overview
OOP's overview
Object-oriented programming (OOP) is the core ingredient of the .NET framework. OOP is so important that,
before embarking on the road to .NET, you must understand its basic principles and terminology to write even a
simple program. The fundamental idea behind OOP is to combine into a single unit both data and the methods
that operate on that data; such units are called an object. All OOP languages provide mechanisms that help you
implement the object-oriented model. They are encapsulation, inheritance, polymorphism and reusability. Let's
now take a brief look at these concepts.
Encapsulation
Encapsulation binds together code and the data it manipulates and keeps them both safe from outside interference
and misuse. Encapsulation is a protective container that prevents code and data from being accessed by other
code defined outside the container.
Inheritance
Inheritance is the process by which one object acquires the properties of another object. A type derives from a
base type, taking all the base type members fields and functions. Inheritance is most useful when you need to add
functionality to an existing type. For example all .NET classes inherit from the System.Object class, so a class can
include new functionality as well as use the existing object's class functions and properties as well.
Polymorphism
Polymorphism is a feature that allows one interface to be used for a general class of action. This concept is often
expressed as "one interface, multiple actions". The specific action is determined by the exact nature of
circumstances.
Reusability
Once a class has been written, created and debugged, it can be distributed to other programmers for use in their
own program. This is called reusability, or in .NET terminology this concept is called a component or a DLL. In OOP,
however, inheritance provides an important extension to the idea of reusability. A programmer can use an existing
class and without modifying it, add additional features to it.
Simple "Hello World" C# Program
This simple one-class console "Hello world" program demonstrates many fundamental concepts throughout this
article and several future articles.
Classes and Objects
Classes are special kinds of templates from which you can create objects. Each object contains data and methods
to manipulate and access that data. The class defines the data and the functionality that each object of that class
can contain.
A class declaration consists of a class header and body. The class header includes attributes, modifiers, and the
class keyword. The class body encapsulates the members of the class, that are the data members and member
functions. The syntax of a class declaration is as follows:
Attributes accessibility modifiers class identifier: baselist { body }
Attributes provide additional context to a class, like adjectives; for example the Serializable attribute.
2 | Oops concept
Accessibility is the visibility of the class. The default accessibility of a class is internal. Private is the default
accessibility of class members. The following table lists the accessibility keywords;
Keyword
Description
public
private
protected
Internal
Internal protected
Modifiers refine the declaration of a class. The list of all modifiers defined in the table are as follows;
Modifier
Description
sealed
static
unsafe
Abstract
The baselist is the inherited class. By default, classes inherit from the System.Object type. A class can inherit and
implement multiple interfaces but doesn't support multiple inheritances.
So here in this example the customer class defines fields such as CustID, Name and Address to hold information
about a particular customer. It might also define some functionality that acts upon the data stored in these fields.
C# code
Class with Private Constructor
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace Oops
{
class Customer
3 | Oops concept
{
}
Class with Public Constructor
Example 2 : On instantiating a class with Public Constructor
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace Oops
{
class Customer
{
public int CustomerId;
public string CustomerName;
public string CustomerAddress;
public Customer()
{
CustomerId = 1234;
CustomerName = "Shaila";
CustomerAddress = "Borivali east";
}
public void DisplayCustomerDetails()
{
//Dispay customer details through method
Console.WriteLine("Custmer Id is :"+CustomerId);
Console.WriteLine("Custmer Name is :" + CustomerName);
Console.WriteLine("Custmer Address is :" + CustomerAddress);
4 | Oops concept
}
Access modifiers
Example 3: Access modifiers example This sample build will fail, it is intentionally done
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace Oops
{
class Customer
{
protected int CustomerId;
private string CustomerName;
internal string CustomerAddress;
public string CustomeMobileNum;
protected internal string CustomerOccupation;
public Customer()
{
CustomerId = 1234;
CustomerName = "Shaila";
CustomerAddress = "Borivali east";
CustomeMobileNum = "935866666";
CustomerOccupation = "Student";
}
public void DisplayCustomerDetails()
{
//Dispay customer details through method
Console.WriteLine("Customer Id is :"+CustomerId);
Console.WriteLine("Customer Name is :" + CustomerName);
Console.WriteLine("Customer Address is :" + CustomerAddress);
Console.WriteLine("Customer Mobile number is :" + CustomeMobileNum);
Console.WriteLine("Customer Occupation is :" + CustomerOccupation);
}
}
public class Program
5 | Oops concept
{
}
Partial class
Example 4: Partial class example with void and return function
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace Oops
{
class Customer
{
public int CustomerId;
public string CustomerName;
public string CustomerAddress;
public string CustomeMobileNum;
public string CustomerOccupation;
public Customer()
{
CustomerId = 1234;
CustomerName = "Shaila";
CustomerAddress = "Borivali east";
CustomeMobileNum = "935866666";
CustomerOccupation = "Student";
}
public void DisplayCustomerDetails()
{
//Dispay customer details through method
Console.WriteLine("Customer Id is :"+CustomerId);
Console.WriteLine("Customer Name is :" + CustomerName);
Console.WriteLine("Customer Address is :" + CustomerAddress);
Console.WriteLine("Customer Mobile number is :" + CustomeMobileNum);
Console.WriteLine("Customer Occupation is :" + CustomerOccupation);
}
}
public partial class CustomerFamilyDetails
{
public void FatherDetails()
{
Console.WriteLine("My Fathers name is :--");
6 | Oops concept
}
}
public partial class CustomerFamilyDetails
{
public string MotherDetails(string mothersName)
{
return mothersName;
}
}
Sealed class
using System;
class Class1
{
static void Main(string[] args)
{
SealedClass sealedCls = new SealedClass();
int total = sealedCls.Add(4, 5);
Console.WriteLine("Total = " + total.ToString());
}
}
// Sealed class
sealed class SealedClass
7 | Oops concept
{
public int Add(int x, int y)
{
return x + y;
}
}
Static class
Exmaple 5 : Static class example
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace Oops
{
class Customer
{
public int CustomerId;
public string CustomerName;
public string CustomerAddress;
public string CustomeMobileNum;
public string CustomerOccupation;
public Customer()
{
CustomerId = 1234;
CustomerName = "Shaila";
CustomerAddress = "Borivali east";
CustomeMobileNum = "935866666";
CustomerOccupation = "Student";
}
public void DisplayCustomerDetails()
{
//Dispay customer details through method
Console.WriteLine("Customer Id is :"+CustomerId);
Console.WriteLine("Customer Name is :" + CustomerName);
Console.WriteLine("Customer Address is :" + CustomerAddress);
Console.WriteLine("Customer Mobile number is :" + CustomeMobileNum);
Console.WriteLine("Customer Occupation is :" + CustomerOccupation);
}
}
public partial class CustomerFamilyDetails
{
public void FatherDetails()
{
Console.WriteLine("My Fathers name is :--");
}
}
8 | Oops concept
public partial class CustomerFamilyDetails
{
public string MotherDetails(string mothersName)
{
return mothersName;
}
}
public static class StaticCutomer
{
public static string staticCustomerName;
public static int staticCustomerId;
public static void DisplayStaticCustomerDetails()
{
staticCustomerId = 258;
staticCustomerName = "Static Customer";
Console.WriteLine("Static customer Id is :"+staticCustomerId);
Console.WriteLine("Static customer name is :"+staticCustomerName);
}
}
public class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
CustomerFamilyDetails customerFamilyDetails=new CustomerFamilyDetails();
customer.DisplayCustomerDetails();
//Display customer Details through object
Console.WriteLine("Custmer Id is :" + customer.CustomerId);
Console.WriteLine("Custmer Name is :" + customer.CustomerName);
Console.WriteLine("Custmer Address is :" + customer.CustomerAddress);
Console.WriteLine("Custmer Mobile number is :" + customer.CustomeMobileNum);
Console.WriteLine("Custmer Occupation is :" + customer.CustomerOccupation);
customerFamilyDetails.FatherDetails();
string motherName=customerFamilyDetails.MotherDetails("Mother");
Console.WriteLine("My mother name is :" + motherName);
StaticCutomer.DisplayStaticCustomerDetails();
Console.ReadLine();
}
}
}
Hiding Methods
If a method with the same signature is declared in both base and derived classes, but the methods are not
declared as virtual and overriden respectively, then the derived class version is said to hide the base class version.
In most cases, you would want to override methods rather than hide them. Otherwise .NET automatically
generates a warning.
In the following example, we are defining a VirutalMethod() in the myBase class but not overriding it in the derived
class, so in that case the compiler will generate a warning. The compiler will assume that you are hiding the base
class method. So to overcome that problem, if you prefix the new keyword in the derived class method then the
compiler will prefer the most derived version method. You can still access the base class method in the derived
class by using the base keyword.
C# code
9 | Oops concept
using System;
namespace oops
{
class myBase
{
//virtual function
public virtual void VirtualMethod()
{
Console.WriteLine("virtual method defined in the base class");
}
}
class myDerived : myBase
{
// hiding the implementation of base class method
public new void VirtualMethod()
{
Console.WriteLine("virtual method defined in the Derive class");
//still access the base class method
base.VirtualMethod();
}
}
class virtualClass
{
static void Main(string[] args)
{
// class instance
new myDerived().VirtualMethod();
Console.ReadKey();
}
}
}
System;
System.Collections.Generic;
System.Linq;
System.Text;
LibraryUtility;
namespace Oops
{
class Customer
{
public int CustomerId;
public string CustomerName;
public string CustomerAddress;
public string CustomeMobileNum;
public string CustomerOccupation;
public Customer()
{
CustomerId = 1234;
CustomerName = "Shaila";
CustomerAddress = "Borivali east";
CustomeMobileNum = "935866666";
10 | O o p s c o n c e p t
CustomerOccupation = "Student";
}
public partial class CustomerFamilyDetails
{
public void FatherDetails()
{
Console.WriteLine("My Fathers name is :--");
}
}
public partial class CustomerFamilyDetails
{
public string MotherDetails(string mothersName)
{
return mothersName;
}
}
public static class StaticCutomer
{
public static string staticCustomerName;
public static int staticCustomerId;
public static void DisplayStaticCustomerDetails()
{
staticCustomerId = 258;
staticCustomerName = "Static Customer";
Console.WriteLine("Static customer Id is :"+staticCustomerId);
Console.WriteLine("Static customer name is :"+staticCustomerName);
}
}
public class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
CustomerFamilyDetails customerFamilyDetails=new CustomerFamilyDetails();
SalaryCalculation salaryCalculation = new SalaryCalculation();
customer.DisplayCustomerDetails();
//Display customer Details through object
Console.WriteLine("Custmer Id is :" + customer.CustomerId);
Console.WriteLine("Custmer Name is :" + customer.CustomerName);
Console.WriteLine("Custmer Address is :" + customer.CustomerAddress);
Console.WriteLine("Custmer Mobile number is :" + customer.CustomeMobileNum);
Console.WriteLine("Custmer Occupation is :" + customer.CustomerOccupation);
customerFamilyDetails.FatherDetails();
string motherName=customerFamilyDetails.MotherDetails("Mother");
11 | O o p s c o n c e p t
Console.WriteLine("My mother name is :" + motherName);
StaticCutomer.DisplayStaticCustomerDetails();
salaryCalculation.CalculateHRABasic(5000,2000);
int reimbursment=salaryCalculation.GetReinbursment(1500);
Console.WriteLine("The reimbursment calcualted is "+reimbursment);
}
}
Console.ReadLine();
Polymorphism in C#
Polymorphism means many forms (ability to take more than one form). In Polymorphism poly means multiple and
morph means forms so polymorphism means many forms.
In polymorphism we will declare methods with same name and different parameters in same class or methods with
same name and same parameters in different classes. Polymorphism has ability to provide different
implementation of methods that are implemented with same name.
In Polymorphism we have 2 different types those are
<!--[if !supportLists]-->
<!--[if !supportLists]-->
binding)
12 | O o p s c o n c e p t
Method Overriding?
Ans:
Method overriding means having a different implementation of the same method in the inherited class. These
two methods would have the same signature, but different implementation. One of these would exist in the base
class and another in the derived class. These cannot exist in the same class.
Overriding methods
Overriding method definitions
In a derived class, if you include a method definition that has the same name and exactly the same number and
types of parameters as a method already defined in the base class, this new definition replaces the old definition
of the method.
Run Time Polymorphism
Run time polymorphism also called as late binding or method overriding or dynamic polymorphism. Run time
polymorphism or method overriding means same method names with same signatures.
In this run time polymorphism or method overriding we can override a method in base class by creating similar
function in derived class this can be achieved by using inheritance principle and using virtual & override
keywords.
In base class if we declare methods with virtual keyword then only we can override those methods in derived class
using override keyword
Overloading concept :
Function overloading allows multiple implementations of the same function in a class. Overloaded methods share
the same name but have a unique signature. The number of parameters, types of parameters or both must be
different. A function can't be overloaded on the basis of a different return type alone.
13 | O o p s c o n c e p t
using System.Linq;
using System.Text;
using LibraryUtility;
namespace Oops
{
class Customer
{
public int CustomerId;
public string CustomerName;
public string CustomerAddress;
public string CustomeMobileNum;
public string CustomerOccupation;
public Customer()
{
CustomerId = 1234;
CustomerName = "";
CustomerAddress = "";
CustomeMobileNum = "";
CustomerOccupation = "";
}
public Customer(int id)
{
CustomerId = id;
}
public Customer(int customerId,string customerName)
{
CustomerId = customerId;
CustomerName = customerName;
}
}
public class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
//Display customer Details through object with constructor having no parameter
Console.WriteLine("Custmer Id is :" + customer.CustomerId);
Console.WriteLine("Custmer Name is :" + customer.CustomerName);
Console.WriteLine("Custmer Address is :" + customer.CustomerAddress);
Console.WriteLine("Custmer Mobile number is :" + customer.CustomeMobileNum);
Console.WriteLine("Custmer Occupation is :" + customer.CustomerOccupation);
Console.WriteLine("---------------Overloading with Customer Id---------------");
Customer customerId=new Customer(8596);
Console.WriteLine("Customer Id is :" + customerId.CustomerId);
}
}
Overriding :
14 | O o p s c o n c e p t
15 | O o p s c o n c e p t
}
}
Console.ReadLine();
Encapsulation
Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both safe
from outside interference and misuse. In OOP, code and data may be combined in such a way that a self-contained
box is created. When code and data are linked together in this way, an object is created and encapsulation exists.
Within an object, code, data or both may be private or public to that object. Private code is known to and
accessible only by another part of the object, that is private code or data may not be accessible by a piece of the
program that exists outside the object. When the code and data is public, other portions of your program may
access it even though it is defined within an object.
C# code
using System;
namespace oops
{
class Encapsulation
{
/// <summary>
/// Every member Variable and Function of the class are bind
/// with the Encapsulation class object only and safe with
/// the outside inference
/// </summary>
// Encapsulation Begin
int x;
//class constructor
public Encapsulation(int iX)
{
this.x = iX;
}
//calculating the square
public void MySquare()
{
int Calc = x * x;
Console.WriteLine(Calc);
}
// End of Encapsulation
//Entry point
static void Main(string[] args)
{
//instance created
customer obj = new customer(20);
obj. MySquare();
16 | O o p s c o n c e p t
}
}
}
Inheritance
Inheritance is the process by which one object can acquire the properties of another object. Inheritance is a "is a
kind of" relationship and it supports the concept of classification in which an object needs only define those
qualities that make it unique within the class. Inheritance involves a base class and a derived class. The derived
class inherits from the base class and also can override inherited members as well as add new members to extend
the base class.
A base type represents the generalization, whereas a derived type represents a specification of an instance. Such
as Employees that can have diverse types, such as hourly, salaried and temporary so in that case Employees is the
general base class and hourly, salaried and temporary employee are specialized derived classes.
Classes can inherit from a single class and one or more interfaces. When inheriting from a class, the derived class
inherits the members including the code of the base class. The important point to remember is that Constructors
and Destructors are not inherited from the base class.
The syntax of inheritance is as in the following;
Class derivedClass : baseClass, Iterface1, Interface2 { body }
For example we are defining two classes, Father and Child. You notice at line 7, we are implementing inheritance
by using a colon (:); at this moment all the properties belonging to the Father Class is accessible to the Child class
automatically.
C# code
using System;
namespace oops
{
//Base Class
public class Father
{
17 | O o p s c o n c e p t
public void FatherMethod()
{
Console.WriteLine("this property belong to Father");
}
}
//Derived class
public class Child : Father
{
public void ChildMethod()
{
Console.WriteLine("this property belong to Child");
}
}
class Inheritance
{
//Entry point
static void Main(string[] args)
{
Father fObj = new Father();
fObj.FatherMethod();
//Here Child object can access both class methods
Child cObj = new Child();
cObj.FatherMethod();
cObj.ChildMethod();
}
}
}
Abstract Class :
Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes
that only represent base classes, and dont want anyone to create objects of these class types. You can make use
of abstract classes to implement such functionality in C# using the modifier 'abstract'.
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
Features:
1.
An abstract class can inherit from a class and one or more interfaces.
2.
3.
4.
5.
18 | O o p s c o n c e p t
6.
7.
8.
using System;
namespace abstractSample
{
//Creating an Abstract Class
abstract class absClass
{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}
19 | O o p s c o n c e p t
The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within
the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers.
You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make
the implementation of the abstract methods of the parent class.
Example
Collapse | Copy Code
//Abstract Class1
abstract class absClass1
{
public abstract int AddTwoNumbers(int Num1, int Num2);
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}
//Abstract Class2
abstract class absClass2:absClass1
{
//Implementing AddTwoNumbers
public override int AddTwoNumbers(int Num1, int Num2)
{
return Num1+Num2;
}
}
//Derived class from absClass2
class absDerived:absClass2
{
//Implementing MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1*Num2;
}
}
In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The
AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and
the MultiplyTwoNumbers is implemented there.
Abstract properties
Following is an example of implementing abstract properties in a class.
Collapse | Copy Code
//Abstract Class with abstract properties
abstract class absClass
{
protected int myNumber;
public abstract int numbers
{
get;
set;
}
}
class absDerived:absClass
{
//Implementing abstract properties
20 | O o p s c o n c e p t
21 | O o p s c o n c e p t
Interface :
Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions from
different classes through the same Interface reference, whereas using virtual functions we can invoke functions
from different classes in the same inheritance hierarchy through the same reference. Before things start getting
difficult let me start using simple and short examples to explain the concept of interfaces. Here's a short example
that shows you what an interface looks like.
P1.cs
Collapse | Copy Code
class Demo
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
}
}
interface abc
{
}
Output
Collapse | Copy Code
Hello Interfaces
The above program compiles and runs successfully to produce the desired output. The above program consists of a
class Demo and within it an entry point function Main() that prints Hello Interfaces. The above program also
defines an interface abc. Interface abc is empty at this point of time. Let's add some elements to this interface.
P2.cs
Collapse | Copy Code
class Demo
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
}
}
interface abc
{
int x;
}
Output
22 | O o p s c o n c e p t
Collapse | Copy Code
P2.cs(11,3): error CS0525: Interfaces cannot contain fields
Error! Interfaces in C# cannot contain fields i.e variables. The above program declared an integer variable x in the
interface abc. And that's what hit the C# compiler badly.
P3.cs
Collapse | Copy Code
class Demo
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
}
}
interface abc
{
void xyz()
{
System.Console.WriteLine("In xyz");
}
}
Output
Collapse | Copy Code
P3.cs(11,8): error CS0531: 'abc.xyz()': interface members cannot have a
definition
This time over we included a function xyz() inside the interface found that this too hurt the C# compiler. It told us
loudly that interface members cannot have a defination. Does this mean that if we just have a function declaration
inside the interface abc that is fine with the C# compiler? Let's find it out.
P4.cs
Collapse | Copy Code
class Demo
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
}
}
interface abc
{
void xyz();
}
Output
23 | O o p s c o n c e p t
Collapse | Copy Code
Hello Interfaces
The above program compiles and runs successfully to produce the desired output. Finally we made the compiler
happy. Interfaces in C# can only contain function declarations. Now let us see interfaces in action.
Interfaces are contracts that a class implements in its own way. This means an interface will contain function
prototypes and a class that marries this interface will have to take the responsibility of defining the functions
whose prototypes are declared by the marrying interface.
So its time to perform the marriage between our groom class Demo and the bride interface abc.
P4.cs
Collapse | Copy Code
class Demo : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
}
}
interface abc
{
void xyz();
}
Output
Collapse | Copy Code
P4.cs(1,7): error CS0535: 'Demo' does not implement interface member
'abc.xyz()'
P4.cs(11,8): (Location of symbol related to previous error)
Well, in the above program class Demo did marry the interface abc through the line class demo : abc but as usual
there's a small misunderstanding between the newlyweds. Class Demo needs to take the responsibility of defining
the functions whose prototypes are declared by the marrying interface abc. Since class Demo in the above program
has not been implemented i.e. defined the function xyz whose prototype is declared by the marrying interface abc
we get an error in the above program. To fix this issue, the class Demo has to take the responsiility of defining the
function xyz whose prototype is declared by the marrying interface abc. And that is what you get to see in the
following program.
P5.cs
Collapse | Copy Code
class Demo : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
}
void xyz()
24 | O o p s c o n c e p t
{
}
System.Console.WriteLine("In xyz");
}
interface abc
{
void xyz();
}
Output
Collapse | Copy Code
a.cs(1,7): error CS0536: 'Demo' does not implement interface member
'abc.xyz()'.'Demo.xyz()' is either static, not public,
or has the wrong return type.
a.cs(16,8): (Location of symbol related to previous error)
a.cs(7,8): (Location of symbol related to previous error)
Error again! It's not enough for the class Demo to implement the function xyz. It has to impress the bride interface
abc by declaring its implementation of xyz as public. And that's what is done by the following program.
P6.cs
Collapse | Copy Code
class Demo : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
xyz();
}
interface abc
{
void xyz();
}
Output
Collapse | Copy Code
Hello Interfaces
In xyz
Bingo! The above program compiles and runs successfully to produce the desired output. As mentioned earlier
using interfaces we can invoke functions from different classes using the same interface reference. For this, we
need to have different classes to implement the same interface. In the above program our class Demo is
implementing the interface abc. Let's have another class Sample that implements the interface abc.
25 | O o p s c o n c e p t
P7.cs
Collapse | Copy Code
class Demo : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
refDemo.xyz();
Sample refSample = new Sample();
refSample.xyz();
}
interface abc
{
void xyz();
}
class Sample : abc
{
public void xyz()
{
System.Console.WriteLine("In Sample :: xyz");
}
}
Output
Collapse | Copy Code
In Demo :: xyz
In Sample :: xyz
The above program compiles and runs successfully to produce the desired output. refDemo is a reference to the
object of class Demo. refSample is a reference to the object of class Sample. Both the classes implement the
interface abc and hence define their own implementation of the function xyz(). From within the entry point
function Main() xyz() of the respective classes Demo and Sample are invoked through references refDemo and
refSample.
Now that we have two different classes implementing the same interface its time to show you how to invoke
functions from different classes using the same interface reference.
P8.cs
Collapse | Copy Code
class Demo : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
26 | O o p s c o n c e p t
interface abc
{
void xyz();
}
class Sample : abc
{
public void xyz()
{
System.Console.WriteLine("In Sample :: xyz");
}
}
Output
Collapse | Copy Code
In Demo :: xyz
In Sample :: xyz
The above program compiles and runs successfully to produce the desired output. Inside Main() we have an
interface reference refabc of type interface abc. Reference of object of class Demo is stored in refabc and xyz() of
class Demo is invoked using refabc. Next, the reference of object of class Sample is stored in refabc and xyz() of
class Sample is invoked using refabc. Thus, we were able to invoke xyz() that belongs to different classes Demo
and Sample via a common interface reference refabc.
The following program uses a for loop to invoke the functions of different classes Demo and Sample that
implement the same interface "interface abc" using a single interface reference refabc whose type matches the
interface "interface abc" which the classes impliment.
P9.cs
Collapse | Copy Code
class Demo : abc
{
public static void Main()
{
abc [] refabc = {new Demo(), new Sample()} ;
for (int i = 0; i<= 1; i++)
refabc[i].xyz();
}
public void xyz()
{
System.Console.WriteLine("In Demo :: xyz");
27 | O o p s c o n c e p t
}
}
interface abc
{
void xyz();
}
class Sample : abc
{
public void xyz()
{
System.Console.WriteLine("In Sample :: xyz");
}
}
Output
Collapse | Copy Code
In Demo :: xyz
In Sample :: xyz
The above program compiles and runs successfully to produce the desired output. refabc is an array of type
interface abc. It stores the references to objects of classes Demo and Sample. In the for loop, using the array
refabc, we are invoking the function xyz() of class Demo and Sample. A class can impliment as many interfaces as
it wants. Take the following program.
P10.cs
Collapse | Copy Code
class Demo : abc, def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
abc refabc = new Demo();
refabc.xyz();
}
public void xyz()
{
System.Console.WriteLine("In xyz");
}
public void pqr()
{
System.Console.WriteLine("In xyz");
}
}
interface abc
{
void xyz();
}
interface def
{
28 | O o p s c o n c e p t
void pqr();
}
Output
Collapse | Copy Code
Hello Interfaces
In xyz
The above program compiles and runs successfully to produce a desired output. Class Demo implements interface
abc and thereby function xyz(). Class Demo also impliments interface def and thereby function pqr(). ref abc
which is a variable of type Interface abc, refers to object of class Demo. Next xyz() of Demo is invoked via refabc
as refabc is a variable of type Interface abc which contains the prototype for function xyz().
P11.cs
Collapse | Copy Code
class Demo : abc, def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
abc refabc = new Demo();
refabc.xyz();
refabc.pqr();
}
public void xyz()
{
System.Console.WriteLine("In xyz");
}
public void pqr()
{
System.Console.WriteLine("In xyz");
}
}
interface abc
{
void xyz();
}
interface def
{
void pqr();
}
Output
Collapse | Copy Code
P11.cs(9,5): error CS0117: 'abc' does not contain a definition for 'pqr'
29 | O o p s c o n c e p t
Error! An attempt to invoke pqr() of Demo via refabc fails as refabc is a variable of type Interface abc which
contains the prototype for function xyz() and NOT pqr(). One can invoke pqr() of Demo via a reference variable of
type Interface def as the interface def contains the prototype for function pqr(). And that's what is done by the
following program.
P12.cs
Collapse | Copy Code
class Demo : abc, def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
abc refabc = refDemo;
refabc.xyz();
def refdef = refDemo;
refdef.pqr();
}
public void xyz()
{
System.Console.WriteLine("In xyz");
}
interface abc
{
void xyz();
}
interface def
{
void pqr();
}
Output
Collapse | Copy Code
Hello Interfaces
In xyz
In pqr
The above program compiles and runs successfully to produce a desired output. Class Demo impliments the
interfaces abc and def. An object of class Demo is created and its reference is stored in refDemo. refabc which is a
variable of type Interface abc, refers to the object of class Demo. Next xyz() of Demo is invoked via refabc as
refabc is a variable of type Interface abc which contains the prototype for function xyz(). Similarly, refdef which is
a variable of type Interface def, refers to object of class Demo. Next pqr() of Demo is invoked via refdef as refdef
is a variable of type Interface def which contains the prototype for function pqr().
P13.cs
30 | O o p s c o n c e p t
Collapse | Copy Code
class Demo : abc, def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
abc refabc = refDemo;
refabc.xyz();
def refdef = refDemo;
refdef.xyz();
}
interface abc
{
void xyz();
}
interface def
{
void xyz();
}
Output
Collapse | Copy Code
Hello Interfaces
In xyz
In xyz
The above program compiles and runs successfully to produce a desired output. Both the interfaces abc and def
declare the prototypes for function xyz(). Class Demo implements interfaces abc as well as def and defines the
function xyz() as well. Thus we can invoke the function xyz() through either of the interface reference variables
(refabc or refdef) after storing the reference to the object of class Demo in refabc or refdef. This poses a
question, how can we have an implementation of xyz that is specific to interface abc and implementation of xyz
that is specific to def inside class Demo? Well, for this we need to use the fully qualified names as in the following
program.
P14.cs
Collapse | Copy Code
class Demo : abc, def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
abc refabc = refDemo;
refabc.xyz();
def refdef = refDemo;
31 | O o p s c o n c e p t
refdef.xyz();
}
public void abc.xyz()
{
System.Console.WriteLine("In abc.xyz");
}
public void def.xyz()
{
System.Console.WriteLine("In def.xyz");
}
}
interface abc
{
void xyz();
}
interface def
{
void xyz();
}
Output
Collapse | Copy Code
a.cs(13,15): error CS0106: The modifier 'public' is not valid for this item
a.cs(18,15): error CS0106: The modifier 'public' is not valid for this item
Bummer! We used the fully qualified name and we got an error. That's because when we use fully qualified names
for functions whose prototypes are a part of interfaces, the compiler doesn't need decorators like public. So we
decided to remove the access specifier public from the above program.
P15.cs
Collapse | Copy Code
class Demo : abc, def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
abc refabc = refDemo;
refabc.xyz();
def refdef = refDemo;
refdef.xyz();
}
void abc.xyz()
{
System.Console.WriteLine("In abc.xyz");
}
void def.xyz()
{
32 | O o p s c o n c e p t
System.Console.WriteLine("In def.xyz");
}
}
interface abc
{
void xyz();
}
interface def
{
void xyz();
}
Output
Collapse | Copy Code
Hello Interfaces
In abc.xyz
In def.xyz
The above program compiles and runs successfully to produce a desired output. A fully qualified naming system
allows us to define interfaces having same function prototypes. In the above example, interface abc and def
contain the same function prototypes for function xyz(). Class Demo impliments both the interfaces. Using fully
qualified names, it defines implementation of xyz that is specific to interface abc and implementation of xyz that
is specific to interface def.
P16.cs
Collapse | Copy Code
class Demo : def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
def refdef = refDemo;
refdef.xyz();
refdef.pqr();
}
public void xyz()
{
System.Console.WriteLine("In xyz");
}
public void pqr()
{
System.Console.WriteLine("In pqr");
}
}
interface abc
{
void xyz();
33 | O o p s c o n c e p t
}
interface def : abc
{
void pqr();
}
Output
Collapse | Copy Code
Hello Interfaces
In xyz
In pqr
The above program compiles and runs successfully to produce a desired output. Interfaces support inheritance.
Interface def inherits prototypes from interface abc. Class Demo implements the interface def. Interface variable
refdef stores the reference to object of class Demo. Functions xyz() and pqr() of class Demo are invoked through
interface reference variable refdef.
What do you think of the fully qualified names of xyz() and pqr() would be after interface def inherits from
interface abc.
P17.cs
Collapse | Copy Code
class Demo : def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
def refdef = refDemo;
refdef.xyz();
refdef.pqr();
}
void def.xyz()
{
System.Console.WriteLine("In xyz");
}
void def.pqr()
{
System.Console.WriteLine("In pqr");
}
}
interface abc
{
void xyz();
}
interface def : abc
{
void pqr();
34 | O o p s c o n c e p t
}
Output
Collapse | Copy Code
P17.cs(12,8): error CS0539: 'def.xyz' in explicit interface declaration is
not a member of interface
P17.cs(29,11): (Location of symbol related to previous error)
P17.cs(1,7): error CS0535: 'Demo' does not implement interface member
'abc.xyz()'
P17.cs(26,8): (Location of symbol related to previous error)
Bummer! The prototype of function xyz is an original member of interface abc. Thus, even if interface def inherits
from the interface abc, the fully qualified name of the function xyz() remains as abc.xyz and not def.xyz as done
in the above program. In fact, we got a compiler error. This can be fixed by using the correct fully qualified name
of function xyz() as shown in the following program.
P18.cs
Collapse | Copy Code
class Demo : def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
def refdef = refDemo;
refdef.xyz();
refdef.pqr();
}
void abc.xyz()
{
System.Console.WriteLine("In xyz");
}
void def.pqr()
{
System.Console.WriteLine("In pqr");
}
}
interface abc
{
void xyz();
}
interface def : abc
{
void pqr();
}
Output
Collapse | Copy Code
35 | O o p s c o n c e p t
Hello Interfaces
In xyz
In pqr
The above program compiles and runs successfully to produce a desired output. But there are some pitfalls when
using the fully qualified function names.
P19.cs
Collapse | Copy Code
class Demo : def
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
refDemo.xyz();
refDemo.pqr();
}
void abc.xyz()
{
System.Console.WriteLine("In xyz");
}
void def.pqr()
{
System.Console.WriteLine("In pqr");
}
}
interface abc
{
void xyz();
}
interface def : abc
{
void pqr();
}
Output
Collapse | Copy Code
P19.cs(7,5): error CS0117: 'Demo' does not contain a definition for 'xyz'
P19.cs(8,5): error CS0117: 'Demo' does not contain a definition for 'pqr'
The above program fails to clear the compilation hurdle. refDemo refers to an object of class Demo. We are
invoking xyz() using refDemo(). For C#, xyz() and ddd.xyz() are two different things. It knows that abc.xyz() exists.
It also knows that just xyz() is nowhere in the class. That's why we get an error which says Class Demo does not
contain a definition of xyz(). For C#, abc.xyz() can be invoked by an interface reference of type abc only. Similarly,
def.pqr() can be invoked by an interface reference of type def only.
License
36 | O o p s c o n c e p t
This article has no explicit license attached to it but may contain usage terms in the article text or the download
files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
A class can implement any number of interfaces but a subclass can at most use only one abstract class.
2.
An abstract class can have non-abstract Methods(concrete methods) while in case of Interface all the
methods has to be abstract.
3.
An abstract class can declare or use any variables while an interface is not allowed to do so.
So following Code will not compile :-
interface TestInterface
{
int x = 4; // Filed Declaration in Interface
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
int i = 4;
int k = 3;
public abstract void getClassName();
}
It will generate a compile time error as :Error
37 | O o p s c o n c e p t
4.
An abstract class can have constructor declaration while an interface can not do so.
So following code will not compile :interface TestInterface
{
// Constructor Declaration
public TestInterface()
{
}
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
public TestAbstractClass()
{
}
int i = 4;
int k = 3;
public abstract void getClassName();
}
Above code will generate a compile time error as :Error
So we need to omit constructor declaration from interface in order to compile our code .
Following code compile s perfectly :interface TestInterface
{
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
public TestAbstractClass()
{
}
int i = 4;
int k = 3;
public abstract void getClassName();
}
5.
An abstract Class is allowed to have all access modifiers for all of its member declaration while in
interface we can not declare any access modifier(including public) as all the members of interface
are implicitly public.
Note here I am talking about the access specifiers of the member of interface and not about the
interface.
Following code will explain it better :It is perfectly legal to give provide access specifier as Public (Remember only public is allowed)
public interface TestInterface
{
void getMethod();
38 | O o p s c o n c e p t
string getName();
But the best way of declaring Interface will be to avoid access specifier on interface as well as members
of interface.
interface Test
{
void getMethod();
string getName();
}