Sie sind auf Seite 1von 11

Deccansoft Software Services - MS.NET C# and VB.

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

Constructors and Inheritance:


1. Create a New Project (ConsoleApplication1)
2. Add the following code to the file in that project.
Program to show Inheritance
Option Strict On
Public Class CParent
Public PubA As Integer
Private PriA As Integer
Protected ProA As Integer
Sub New()
End Sub
Sub New(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)
Me.New()
Me.PriA = a
Me.ProA = b
Me.PubA = c
End Sub
End Class

Public Class CChild


Inherits CParent
Public pubB As Integer
Sub New() 'Will call base class constructor
End Sub
Sub New(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer, ByVal d As Integer)
MyBase.New(a, b, c)
Me.pubB = d
End Sub
Public Sub Foo()
Dim p As New CParent
Dim c As New CChild
ProA = 10
c.ProA = 10
'p.ProA = 10 ' Compilation Error because "p" is of type Parent.

2
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance

End Sub
End Class

Public Class Program


Shared Sub Main(ByVal args() As String)
Dim b As CChild
b = New CChild(1, 2, 3, 4)
b.Foo()
End Sub
End Class
Code: 5.1 VB

Program to show Inheritance


using System;
public class CParent
{
public int PubA;
private int PriA;
protected int ProA;
public CParent()
{}
public CParent(int a, int b, int c)
: this()
{
this.PriA = a;
this.ProA = b;
this.PubA = c;
}
}

public class CChild : CParent


{
public int pubB;
public CChild() //First calls parent class constructor.
{}
public CChild(int a, int b, int c, int d)
: base(a, b, c)
{
//this.PriA = a; this.ProA =b; this.PubA = c;
this.pubB = d;
}
public void Foo()
{
CParent p = new CParent();
CChild c = new CChild();
ProA = 10; //Allowed
c.ProA = 10; //Allowed
//p.ProA = 10; //Compilation Error because p is of type parent.
}
}

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

Type Casting of Reference Types


CParent p;
CChild c;
p = new CChild(); //Valid
c = new CParent(); //Invalid and Compilation Error.
A reference variable of type parent can refer to an object of child class because all the members which the
reference variable can access exist in memory when the object is of child class.
A reference variable of child cannot refer to an object of parent class because the child class members that the
reference variable can access do not exist in memory when the object is of parent class.

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

Static and Dynamic Binding


Virtual methods are dynamically bound i.e., the actual method called would be decided at runtime and the decision
is based on the object to which the reference variable invoking the method is referring to.
Methods not declared as virtual are statically bound i.e., the actual method invoked would be decided at compile
time and is based on purely the data type of the reference variable invoking the method irrespective of the object
the reference variable is referring to.
CParent p; -------- virtual virtual
CChild c; new new override
p = new CChild();
p.Foo(); Static Dynamic Dynamic
Compile Runtime Runtime
DataType Object Type Object Type
CParent CParent CChild
using reference variable of type parent - Child class method can execute only if
1. Child class object is created
2. Child class overrides parent class method.

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.

Program for using Overrideable, Overrides


Option Strict On Class CChild Public Class Program
Inherits CParent Shared Sub Main(ByVal args()
Public Class CParent Public Overrides Sub Foo() As String)
Public Overridable Sub Foo() Console.WriteLine("CChild") Dim a As CParent
Console.WriteLine("CParent") End Sub a = New CChild()
End Sub End Class a.Foo()
End Class End Sub
End Class
Code: 5.2 VB

Program for using Virtual, Override


class CParent class CChild : CParent
{ {
public virtual void Foo() public override void Foo()
{ {
Console.WriteLine("CParent"); Console.WriteLine("CChild");
} }
} }
class Program
{
static void Main(string[] args)
{
CParent a = new CChild();
a.Foo();
}

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.

A class declared as sealed cannot be inherited.


A method declared as sealed cannot be overridden in the child class.

All possible combinations of virtual, new, override and sealed keywords.

Parent -- --- -- virtual virtual virtual virtual virtual virtual


new new new new override
Child new virtual virtual new virtual virtual override override sealed
GrandChild new new override new new override new override new
Parent p;
p = new
GrandChild()
p.Foo() Static Static Static Dynamic Dynamic Dynamic Dynamic Dynamic Dynamic
Which method is
executed. Parent Parent Parent Parent Parent Parent Child GrandChild Child

7
Deccansoft Software Services - MS.NET C# and VB.NET Inheritance

Abstract Classes and Methods


1. An abstract method is a method in which declaration is provided but implementation is not.
2. A class with one or more methods declared as abstract must be declared as abstract and such a class cannot
be instantiated because its behavior is incomplete.
3. A class that inherits the abstract class must override all the abstract members of the parent class, if not it
should also be declared as abstract. Abstract = Pure Virtual
4. A class can be declared as abstract even without an abstract member and such a class cannot be instantiated.
5. A class which is not abstract is called as Concrete Class. (concrete is not a keyword)
6. An abstract class can have all types of members which a concrete class can have including constructor,
destructor, static members etc(additionally it can have abstract members which a concrete class cannot
have)
7. A sealed class cannot have abstract methods.
Create a New Console Application and add the following code to the various files added to that project.
Using MustInherit(Abstract version of C#)
MustInherit Class Figure
Public Dimension As Integer
Public MustOverride Function Area() As Double
Public MustOverride Function Perimeter() As Double
End Class

Class Square
Inherits Figure

Public Overrides Function Area() As Double


Return Dimension * Dimension
End Function

Public Overrides Function Perimeter() As Double


Return 4 * Dimension
End Function
End Class

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();

int hash = 10;


hash = (hash * 7) + hashX;
hash = (hash * 7) + hashY;

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

Type tp1 = pt1.GetType();


Type tp2 = pt2.GetType();
Console.WriteLine(tp1 == tp2);

Object ob = new Object();


Console.WriteLine(ob);
}
}
Summary:
In this article, we have studied inheritance and use of constructors along with it. Static and dynamic binding with the
methods and Abstract classes and methods are also covered in this topic.

11

Das könnte Ihnen auch gefallen