C# - OOPS Inheritance - Bestdotnettraining
C# - OOPS Inheritance - Bestdotnettraining
C# - OOPS Inheritance - Bestdotnettraining
NET Inheritance
Agenda
1. Introduction to Inheritance
2. Constructors & Inheritance
3. Type casting of Reference Types
4. Static and dynamic binding
5. Abstract classes
Table of Contents
OVERVIEW 2
STATIC AND DYNAMIC BINDING 6
ABSTRACT CLASSES AND METHODS 8
SYSTEM.OBJECT CLASS 10
1
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
Overview
Inheritance depends upon is a relationship.
For example:
Car is a Vehicle
Faculty is a Person
Student is a Person
Mango is a Fruit
Chair is a Furniture
Scientific Calculator is a Calculator
General syntax:
class CParent
{ }
class CChild : CParent
{ }
2
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
End Sub
End Class
class Program
{
static void Main(string[] args)
{
CChild b;
b = new CChild(1, 2, 3, 4);
3
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
b.Foo();
}
}
Code: 5.1 C#
Notes:
Protected members are accessible only within the class and in derived classes and are not accessible to non-
derived classes
The protected member of parent class cannot be accessed in a child class method using the reference
variable of type parent. For example refer to Foo method in the above CChild class(p.ProA = 10)
When an object of child class is created all the data members of the parent class and child class are allocated
memory irrespective of their access specifier i.e. public or private or protected.
Whenever an object of child class is created, even though the child class constructor is visited first, its the
parent class constructor which is executed first. This is because the child class constructor can then override
the code already executed in parent class constructor.
Every child class constructor by default first calls default constructor of parent class.
Using base in C# (MyBase in VB) and with appropriate arguments a child class constructor can make an
explicit call any other constructor of parent class.
The order of visiting constructor is child class first and then parent because the child class constructor if
required can pass data to the parent class constructor using base
It is recommended that a child class constructor always pass data to the parent class constructor so that the
parent class constructor can initialize the data members of the parent class and the child class constructor
remains with initializing only its own data members.
If the parent class doesnt have default constructor, then every child class constructor must explicitly link to
any other constructor of the parent class.
The order of execution of destructor is child first and then parent which is reverse order of execution of
constructor.
4
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
Note: Using a reference variable of type parent, child class members cannot be accessed even if the object is
of child class.
CParent p; CChild c;
p = c //is Valid Does Implicit casting because the object to which c can refer to is only of type CChild (child class)
and p can also refer to that object.
c = p // is invalid because p can refer to an object of type CParent and CChild but c cannot refer to an object
of type CParent, hence the compiler for such statements give an error.
p = new CChild () ;
c = p; //is still not allowed
c = (CChild) p;
//Explicit Casting is valid but if p refer to an object of type CParent then at runtime InvalidCastException is
thrown
CParent p = new CChild() / CParent();
CChild c = p as CChild; //as is an operator
Console.WriteLine(c == null);
as Operator: if p is referring to an object of type CChild or any of its subclass then the reference is
assigned to c otherwise it assigns null to c (it doesnt throw InvalidCastException)
Is Operator:
o if (p is CChild)
The above condition is true only if p is referring to an object of class CChild or any of its subclass.
"??" Operator:
object y = x ?? z;
// y = x, unless x is null, in which case y = z.
5
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
If the class of the reference variable has the method declared as virtual then it is dynamic binding otherwise its
static binding.
Static binding gives better performance than dynamic binding.
6
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
Code: 5.2 C#
Try the above program with and without virtual and override keywords in both CParent and CChild classes.
If the object is of child class and the child class overrides the method only then the child class method is
executed. Otherwise it will always execute parent class method.
Only virtual methods or overridden methods of parent class can be overridden in the child class.
A method declared as new can also be declared as virtual new and such methods shadows the parent
class method but can be overridden in the child class if needed.
Note: Field members are always statically binded at compile time based on the Data Type of the reference
variable accessing the member. Instance variables cannot be declared as virtual in parent class and thus if a
variable with same name is declared in the child class then it should be declared as new.
7
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
Class Square
Inherits Figure
Class Circle
Inherits Figure
Public Overrides Function Area() As Double
Return Math.PI * Dimension * Dimension
End Function
Public Overrides Function Perimeter() As Double
Return 2 * Math.PI * Dimension
End Function
End Class
Class Program
Sub Main()
Dim fig As Figure = New Square()
fig.Dimension = 10
Console.WriteLine(fig.Area())
Console.WriteLine(fig.Perimeter())
End Sub
End Class
Code: 5.3 VB
8
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
Using Abstract:
using System;
abstract class Figure
{
public int Dimension;
public abstract double Area();
public abstract double Perimeter();
}
class Square : Figure
{
public override double Area()
{
return Dimension * Dimension;
}
public override double Perimeter()
{
return 4 * Dimension;
}
}
class Circle : Figure
{
public override double Area()
{
return Math.PI * Dimension * Dimension;
}
public override double Perimeter()
{
return 2 * Math.PI * Dimension;
}
}
class Program
{
static void Main()
{
Figure fig = new Square(); // or Circle();
fig.Dimension = 10;
Console.WriteLine(fig.Area());
Console.WriteLine(fig.Perimeter());
}
}
Code: 5.3 C#
Output: If Object is of type Square, then the Area and Perimeter of Square is printed. Similarly if the object is of type
Circle then Area and Perimeter of Circle is printed.
9
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
System.Object Class
Every class in .NET is inherited from System.Object class. Thus the functionality in Object class is available to all the
objects in .NET. Also the reference variable of type System.Object can refer to instance/object of any class in .NET
Methods in Object class:
1. bool Equals(object obj) // Compares the current object reference with obj and returns true if both are
referring to the same object otherwise returns false.
2. System.Type GetType() //returns the Type instance for the current objects class.
3. int GetHashCode() //return a unique number using which CLR identifies the current object.
4. string ToString() //return the class name of the current object.
Note: The GetHashCode() method should reflect the Equals logic; the rules are:
1. if two things are equal (Equals(...) == true) then they must return the same value for
GetHashCode()
2. if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and
Equals will be called to see if it is a real equality or not.
class Point : Object
{
public int X, Y;
public override string ToString()
{
return X + " " + Y;
}
public override bool Equals(object obj)
{
Point p = (Point)obj;
return (this.X == p.X) && (this.Y == p.Y);
}
public override int GetHashCode()
{
int hashX = X.GetHashCode();
int hashY = Y.GetHashCode();
return hash;
}
}
class Program
{
static void Main(string[] args)
{
Point pt1 = new Point() { X = 11, Y = 10 };
Console.WriteLine(pt1.ToString());
Point pt2 = new Point() { X = 11, Y = 10 };
Console.WriteLine(pt1.Equals(pt2));
Console.WriteLine(pt1.GetHashCode() + " " + pt2.GetHashCode());
10
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance
11