Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

CSharp.NET Tutorial – Day 12

Tags: class

In previous article, we have discussed what is Inheritance, what are the rules and regulations to be adopted when we are working with Inheritance, what are different Types of Inheritance like Single Inheritance, Multiple Inheritance, etc, how to work with parent Class constructors and child class constructors, How to consume a class from other classes using Inheritance and By creating the object of class, what are Extension Methods, How to Define Extension Methods, what is Polymorphism, what is Method Overloading, what is Constructor Overloading, what is Operator Overloading, what is Inheritance Based Overloading, what is Method Overriding, Differences between Overloading and Overriding, How to Override Parent class’s Method under Child class, What happens when we override Parent class’s virtual methods under child class, what is Method Hiding, what are different types of Polymorphism like Static (or) Compile time Polymorphism and Dynamic (or) Runtime Polymorphism, what is Operator Overloading, what are Sealed Classes and Sealed Methods along with syntaxes and some examples for better understanding, etc

Please find below the link for accessing the article
CSharp.NET Tutorial - Day 11 

Now, in this article we will discuss what are Abstract Classes and Abstract Methods, a brief discussion on what is Interface, in how many ways we can categorize inheritance i.e. Implementation Inheritance and Interface Inheritance, what is Structure, what are differences between Class and Structure, what are Access Specifiers like private, internal, protected, protected internal, public along with syntaxes and examples.

Abstract Classes and Abstract Methods
A Method without any method body is known as an ‘Abstract method.’  It contains only the ‘signature’ or ‘declaration.’

In order to define an Abstract method, we need to use ‘Abstract’ modifier on the method which we are going to use an abstract method.

If any class contains these abstract methods can be referred as an ‘Abstract class,’ and it should also be declared using ‘Abstract’ modifiers.

abstract class Class1
{
public abstract void Add(int x, int y);
}

Here, the concept of abstract methods is very much similar to the concept of ‘method overriding.’  In case of overriding, parent class declares any of its methods as ‘virtual’ means that giving permission to the child class for re-implementing the methods whereas in case of abstract methods, parent class declares any of its methods as abstract asking the child classes to implement the abstract methods and it is mandate for child classes to implement.

Abstract Classes
An abstract class, we can define either abstract or non-abstract methods, but the thing is that if any of its child class wants to consume its non-abstract methods first it should give the implementation for all abstract methods then only it can be consumed non-abstract methods.  So, it is mandate to implement abstract methods first in any case.



Note:  An Abstract class is not at all useful to itself because we cannot create an object of it.

Add a class ‘AbstractParent.cs’ and write the below by making the class as ‘Abstract’

abstract class AbstractParent
{
public void Add(int x, int y)
{
Console.WriteLine(x+y);
}
public void Sub(int x, int y)
{
Console.WriteLine(x-y);
}

public abstract void Mul(int x, int y);
public abstract void Div(int x, int y);
}

Add a class ‘AbstractChild.cs’ and write the below

class AbstractChild : AbstractParent
{
public override void Mul(int x, int y)
{
Console.WriteLine(x*y);
}
public override void Div(int x, int y)
{
Console.WriteLine(x/y);
}
static void Main()
{
AbstractChild obj=new AbstractChild ();
obj.Add (100, 45);
obj.Sub (43, 34);
obj.Mul (454, 45);
obj.Div (43, 23);
Console.ReadLine ();
}
}

Note:  Though there no option to create object of an abstract class, still we can create reference of it using child class object and with that reference, we can call the non-abstract methods of abstract class as well as abstract methods of abstract class which are implemented under child class.

To test this, rewrite the code under child class Main method as below

AbstractChild obj = new AbstractChild();
AbstractParent p = obj;
p.Add(100, 68);
p.Sub(43, 32);
p.Mul(55, 454);
p.Div(43, 32);
Console.ReadLine();


Note:  Abstract class can be used for providing properties to its child class as well as for imposing restrictions on its child classes also.

In the above example, ‘Figure.cs’ is an abstract class which contains all the common attributes that can be used under different figures like Rectangle, Circle, Triangle, Cone, etc and it also contains two abstract methods i.e. GetArea() and GetPerimeter() for imposing restrictions on all its child classes i.e. the child classes should be implemented those two methods separately according to the type of Figure it is.

Note:  Abstract classes are always Parent classes only.  So, these are always sit on the top of the hierarchy.

Add a class ‘Figure.cs’ and write the below

public abstract class Figure
{
public double width,height,radius;
public const float pi=3.14f;
public abstract double GetArea();
public abstract double GetPermieter();
}

Add a class ‘Rectangle.cs’ and write the below

public class Rectange : Figure
{
public Rectangle(double width, double height)
{
//Here using 'this' or 'base' will be same
this.width=width;
base.height=height;
}
public override double GetArea()
{
return width * height;
}
public double GetPermieter()
{
return 2*(width+height)
}
}

Add a class ‘Circle.cs’ and wirte the below

public class Circle : Figure
{
public Circle(double radius)
{
this.radius=radius;
}
public override double GetArea()
{
return pi*radius*radius;
}
public override double GetPerimeter()
{
return 2*pi*radius;
}
}

Add a class ‘TestFigure.cs’ and write the below

class TestFigures
{
static void Main()
{
Rectangle r=new Rectangle(12.45,43.23);
Console.WriteLine(r.GetArea());
Console.WriteLine(r.GetPermieter());
Circle c=new Circle(32.43);
Console.WriteLine(c.GetArea());
Console.WriteLine(c.GetPerimeter());
Console.ReadLine();
}
}

Interface

Like a class, Interface is also a ‘type,’ but it can only contain ‘abstract’ members.  A small difference in between interface, class and abstract class is as follows.

Interface
Only Abstract Members
Class
Only Non-Abstract Members
Abstract Class
Both Abstract and Non-Abstract Members

Whatever the rules we have discussed in case of abstract class those all are applied to an interface also i.e. the implementation of abstract methods which are declared inside the interface should be implemented by its children.

Mainly, interfaces are used in distributed application development i.e. applications which execute in Client Server Architecture.

Multiple inheritance is possible with interfaces i.e. a class can have only one class as its immediate parent, but the same class can have any number of interfaces as its parent.

Inheritance can be categorized in two types

a)      Implementation Inheritance
b)      Interface Inheritance

If a class is inheriting from another class, we call it as ‘implementation inheritance’.

In java and .NET Languages, this is only single, whereas if class is inheriting from an interface we call it as interface inheritance but this is “multiple” in all object oriented programming languages.

Syntax for Interface

[<modifiers>] interface <Name>
{
-declaration of Abstract Members
}

Note:
1.      We cannot define any variables in interfaces
2.      ‘Public’ is the default scope of members in interface
3.      By default, all interface members are abstract and it does not require any explicit declaration
4.      Like a class can inherit from another class, an interface can inherit from another interface but not from class

Add an Interface item ‘Inter1.cs’ and write the below

Interface Inter1
{
void Add(int x,int y);
void Sub(int x,int y);
void Test();
}

Add another Interface item ‘Inter2.cs’ and write the below

Interface Inter2
{
void Mul(int x, int y);
void Div(int x,int y);
void Test();
}

To implement the method of both these interfaces, add a class ‘InterClass.cs’ and write the below

class InterClass:Inter1,Inter2
{
public void Add(int x,int y)
{
Console.WriteLine(x+y);
}
public void Sub(int x,int y)
{
Console.WriteLine(x-y);
}
public void Mul(int x,int y)
{
Console.WriteLine(x*y);
}
public void Div(int x,int y)
{
Console.WriteLine(x/y);
}

Resolving Ambiguity problem with Interface Methods

Solution 1:

public void Test()
{
Console.WriteLine("Declared under 2Interfaces and Implemented under class");
}

Solution 2:

void Inter1.Test()
{
Console.WriteLine("Declared under Interface1");
}
void Test2.Test()
{
Console.WriteLine("Declared under Interface2");
}
static void Main()
{
InterClass obj=new InterClass();
obj.Add(43,334);
obj.Sub(34,32);
obj.Mul(43,23);
obj.Div(32,223);

//Calling Ambiguous Method implemented using two solutions
// Calling when implemented using Solution1: obj.Test();

//Calling when implemented using Solution2:
Inter1 i1=obj;
Inter2 i2=obj;
i1.Test();
i2.Test();
Console.ReadLine();
}
}

Previously, we have been discussed that multiple inheritance is not supported through classes because of ambiguity problem, whereas through interfaces we can resolve the problem of ambiguity in two different ways.

In case of class to class inheritance, child class is consuming members of its parent class so ambiguity comes into picture when the class is inheriting from more than one class as there is confusion that which parent class’s methods should be executed so that is the reason that there is restriction for multiple inheritance through classes, but in case of Interface to class inheritance, class is not consuming its parent members it is only implementing them so no question of ambiguity.

Below are the two solutions that we can resolve the problems

1) Implement the ambiguous method of both interfaces only for a single time under the class, where both interfaces assume that their own method is implemented and executed only.  Here, we can call the method directly by using object of the class.

2) We can also implement the ambiguous method of both interfaces separately under the class by prefixing the method with the name of interface.  In this context, while invoking the method, we need to use reference of the interface to which the method is belong to.

Structure

Similar to class, ‘Structure’ is also a ‘type’ and it contains variables, methods, constructors, etc.

Note:  Structure in C# is having more features compared to Structure in traditional C and C++ languages i.e. in traditional languages Structures can contain only variables, but here Structures can contain variables, methods, constructors, etc.

Now, we will see some differences between Class and Structure

Class
Structure
It is ‘reference type’
It is a ‘value type’
Memory Allocation will be done on Managed Heap so it has a support of Garbage Collector for Automatic Memory Management
Memory Allocation will be done on Stack so it has no support for Automatic Memory Management, but faster in access
It requires a ‘new’ operator for creating the object
Using ‘new’ operator to create object is only optional
It can contain variable declarations and initializations also
It can contain variable declarations, but we cannot initialize the variables.  Initialization of structure variable can be done either under constructor or assign the value directly to the variable referring it with the object
It requires a constructor for creating the object, which need not be a default constructor
It requires a constructor for creating the object, but must contain default constructor, which will be used when the object is created without using new operator
Because constructor is mandate for object creation if there is no constructor in the class compiler defines a constructor for the class which will be parameterless (default)
Every structure will have implicit default constructor which cannot be defined by the programmer at all.  A programmer can define only parameterized constructor
If we defined with ‘0’ constructors, after compilation there will be ‘1’ constructor and if we defined with ‘n’ constructors, after compilation there will be ‘n’ constructors only
If we defined with ‘0’ constructors, after compilation there will be ‘1’ constructor and if we defined with ‘n’ constructors, after compilation there will be ‘n+1’ constructors
It supports both implementation inheritance and interface inheritance.
It supports only interface inheritance which cannot be called like reusability

Syntax for Structure

[<modifiers>] struct <name>
{
-statements
}

Add a ‘code file’ in the Project naming it as ‘StructEx.cs’ and write the below

Note:  A ‘code file’ is a blank file with ‘.cs’ extension in which we can define a class or interface or structure.

using System;
namespace OOPSProject
{
struct StructEx
{
int x;
public StructEx(int x)
{
this.x=x;
}
public void Display()
{
Console.WriteLine("Method under structures:"+x);
}
static void Main()
{
StructEx m1; //Invokes default constructor
m1.x=100;
m2.Display();
StructEx m2=new StructEx(200);
m2.Display();
Console.ReadLine();
}
}
}

Though structure does not support inheritance, it can be consumed from a class or another structure by creating its object.

Add another code file ‘StructEx2.cs’ and write the below

using System;
namespace OOPSProject
{
struct StructEx2
{
static void Main()
{
StructEx obj=new StructEx(300);
obj.Display();
Console.ReadLine();
}
}
}

We can be implemented predefined types, which comes under the value type category in the form of structures.

Eg:  int32, int64, single, Boolean etc

All the predefined data types, which will come under the reference type category are implemented as classes

Eg:  string and object

Access Specifiers

Access specifiers are also modifiers which are used to define scope of a ‘type’ (class or interface or structure) as well as their members i.e. who can access them and who cannot access them.

Basically, C# supports five types of access specifiers, which are listed below

1)      private
2)      internal
3)      protected
4)      protected internal
5)      public

Note:  Members defined in a ‘type’ with any scope (specifiers) are always accessible within that ‘type’ and the restriction comes into picture only when we try to access them outside of the ‘type.’  Now we will look into one by one.

1) private
Members declared as ‘private’ under class or structure are not accessible outside of the class, in which they are defined.  The default scope of members of a class and a structure is always ‘private’ whereas it is ‘public’ in case of interface.  Interfaces should not contain ‘private’ members in it and also ‘type’ can never be declared as ‘private.’

2) internal
Members or types that are declared as internal are accessible only within the project both from child or non-child.  The default scope of any type in C# is 'internal' only.

3) protected
Members declared as ‘protected’ under class can be accessed only from its child or within itself. A non-child class cannot consume them.  Types cannot be declared as ‘protected.’

4) protected internal
The combination of internal and protected is ‘protected internal.’  Members declared as ‘protected internal’ enjoys dual scope i.e. within the project they behave as ‘internal’ providing access everyone in the project and outside of the project, they change to ‘protected’ and still give access to child classes.

5) public
Public means global i.e. a type or a member of type is declared as ‘public’ means global in scope can be accessed from anywhere.

For simply understanding, we place them all access specifiers in a table along with some cases as below

Case1:  Accessing members within the same class
Case2:  Accessing members within child class of same project
Case3:  Accessing members within non-child class of same project
Case4:  Accessing members within child class of other project
Case5:  Accessing members within non-child class of other project


Also, see below diagram for better understanding on access specifiers.


Open Visual Studio, Go to New Project., choose Console application, name it as ‘AccessEx1’ and name the Solution as ‘MySolution.’  As we all know, by default the project comes with a class ‘Program.’  Under the file ‘Program.cs’ write the below code making the class as ‘public’

//Case1

public class Program
{
private void Test1()
{
Console.WriteLine("Private Method"):
}
internal void Test2()
{
Console.WriteLine("Internal Method");
}
protected void Test3()
{
Console.WriteLine("Protected Method");
}
protected internal void Test4()
{
Console.WriteLine("Protected Internal Method");
}
public void Test5()
{
Console.WriteLine("Public Method"):
}

static void Main(string[] args)
{
Program p=new Program();
p.Test1();
p.Test2();
p.Test3();
p.Test4();
p.Test5();
Console.ReadLine();
}
}

Add a new class ‘Two.cs’ in the Project and write the below code

//Case2

class Two:Program
{
static void Main()
{
Two obj=new Two();
obj.Test2();
obj.Test3();
obj.Test4();
obj.Test5();
Console.ReadLine();
}
}

Add a new class ‘Three.cs’ and write the below code

//Case3

class Three
{
static void Main()
{
Program p=new Program();
p.Test2();
p.Test4();
p.Test5();
Console.ReadLine();
}
}

Add a New Project under solution of type Console application name it as ‘AccessEx2’ and rename the default file ‘Program.cs’ as ‘Four.cs.’  So the class name also changes as ‘Four.cs.’  Now, add reference of ‘AccessEx1’ assembly from physical location to the current project and then write the below code.

//Case4

Class:Four:AccessEx1:Program
{
static void Main()
{
Four obj=new Four();
obj.Test3();
obj.Test4();
obj.Test5();
Console.ReadLine();
}
}

Add a new class under the project ‘AccessEx2’ name it as ‘Five.cs’ and write the below code

//Case5

Using AccessEx1;
class Five
{
static void Main()
{
Program p=new Program();
p.Test5();
Console.ReadLine();
}
}

Question. How to restrict a class that is not to be accessible to any other class?
Answer.  This can be done by declaring constructors of class as ‘private’

Question. How to restrict a class that is not to be inherited to any other class?
Answer.  This can be done by declaring class as ‘sealed’

Question. How to restrict a class that is not to be accessible to any other class to consume by creating its object?
Answer.  This can be done by declaring constructor of the class as ‘protected’

Happy Learning….!!!!!

CSharp.NET Tutorial - Day 13


This post first appeared on Dot Net Programming (C#, Asp.Net, ADO.Net, WCF, WPF, Ajax, LINQ), please read the originial post: here

Share the post

CSharp.NET Tutorial – Day 12

×

Subscribe to Dot Net Programming (c#, Asp.net, Ado.net, Wcf, Wpf, Ajax, Linq)

Get updates delivered right to your inbox!

Thank you for your subscription

×