Você está na página 1de 53

Inheritance in c#

Lect.No-15
Date-15-04-2011
Overview
• Introduction
• Need of Inheritance
• Extending Base Classes
• Accessing Base Class Data
• Use of Constructor in Inheritance
• Abstract Class
• Virtual Methods
• Anonymous Types
Introduction
• In programming terms, Inheritance is a process of
inheriting the behavior and properties of existing
classes into new classes.
• The properties of a class includes the data i.e.
Member variables and Methods.
• Inheritance enable the user to reuse , extends, and
modify the code of existing class.
• The class extended into another class is called
Base/Parent/Main Class.
• The class which inherit the Base class is called
Derive/Child/Sub class. Contd…
• For example Human is class and its sub
classes Male and Female inherit features
defined in it. But these classes also have their
own properties.
HUMAN

MALE FEMALE
Example
• Develop a game in which 4 characters used to
perform particular action. Nested Box
represent class name such as Alien, Bandit
and outer boxes contain their data such as
walk, Talk. (Fig 1.)
Here is an Activity !
• Find out the common task performed by each
class in Fig. 1 ?
• Ans: All of the characters seem to share a
Walk, Talk, and Say action. Doesn't it seem a
bit wasteful to code a Walk, Talk, and Say
method for each character separately? If you
think it is wasteful, this is where inheritance
comes in.
• So what’s the solution ?
Solution is…
What it helps in ?
• It make the code more modular by dividing larger
pieces of code into smaller, more maintainable ones.
• It introduce a hierarchy where objects become more
specialized as you move down the tree. A Character
is pretty generic and can just walk, talk, and say
something, but an Alien character, for example, does
all that plus has the ability to teleport and hide.
• Code can be reused now. Instead of coding Walk,
Talk, and Say for each of characters, only code them
once in Character class.
Extending Base Class…
• Syntax for deriving a class from a base class
• Class Base_class
{
......
}
Class Derive_class : Base_class
{
.......
}
Accessing Base Class Data…
• By default class data is of private type.
• Private data is only accessible by the public
methods of the same class.
• Once class is inherited, the object of derived
class can access the methods and variables of
base class.
• The object of derived class is used to call base
class methods as call its own methods
• Derive_obj.base_method(para);
Example
• class base1
{
public int a,b;
public void init()
{
Console.WriteLine(“Enter a & b:”);
a=Convert.ToInt32(Console.ReadLine());
b=Convert.ToInt32(Console.ReadLine());
}
}
contd..
Extending
Base class

class derive1 : base1


{
public void display()
{
Console.WriteLine(“a=“+a+”b=“+b);
}
}

contd…
class main_class
{ Deriv
e
static void Main(string[] args) class
objec
t
{
derive1 d=new derive1();
d.init();
d.display();
Console.ReadKey();
}
}
Here is the output !
Enter a & b: 4
5
a=4
b=5
Constructors in Inheritance…
• As constructors are used to initialize class objects.
By using Derive class constructor ,we can
initialize base class variables.
• For example:
derive1 d=new derive1(1,2,3);
public derive1(int x,int y,int z)
{
a=x;b=y;c=z; //a,b are base class //variables,c is
derive class //variable
}
The Problem is !
• Which constructor should be invoked in case
base class and derive class having constructors ?
Which one should be invoked first ?
• The answer is : we are provided with a keyword
“base” which is used with derive class
constructor and responsible for the invocation
of base class constructor and passing
parameters.
Contd…
Base
• For example: keyword

public derive1(int x,int y,int z):base(x,y)


{
c=z;
}
• class base1
{
public int a,b;
public base1(int x,int y)
{
a=x; b=y;
}
}
class derive1 : base1
{
public int c;
public derive1(int x,int y,int z):base(x,y)
{
c=z;
}
public void display()
{
Console.WriteLine(“a=“+a+”b=“+b+”c=“+c);
}
}
Contd…
class main_class
{
static void Main(string[] args)
{
derive1 d=new derive1(1,2,3);
d.display();
Console.ReadKey();
}
}
Output is:
• a=1
b=2
c=3
Abstract Classes
• A class declared with abstract keyword and
containing at least an abstract method is
known as Abstract Class. It may contain non-
abstract methods.
• Abstract method in abstract class is defined
without implementation.
• Implementation is done in the class which
inheriting the abstract class.
Contd..
• Use of the abstract modifier in a class
declaration to indicate that a class is intended
only to be a base class of other classes.
• An abstract class cannot be initialized.
• It is not possible to modify an abstract class
with the sealed modifier, which means that
the class cannot be inherited.
• A non-abstract class derived from an abstract
class must include actual implementations of
all inherited abstract methods. Contd..
• An abstract method is implicitly a virtual
method. Abstract method declarations are
only permitted in abstract classes. Because an
abstract method declaration provides no
actual implementation, there is no method
body; the method declaration simply ends
with a semicolon and there are no braces ({ })
following the signature. For example:
public abstract void MyMethod();
contd..
• The implementation is provided by an
overriding method, which is a member of a
non-abstract class. It is an error to use the
static or virtual modifiers in an abstract
method declaration.
• For example:

Contd..
• namespace ConsoleApplication3
• {
• abstract class Class5
• {
• public abstract void add(int a, int b);
• }
• class der:Class5
• {
• public override void add(int a, int b)
• {
• int s = a + b;
• Console.WriteLine(s);
• }
• }

• class main_abs
• {
• public static void Main(string[] args)
• {
• der c5 = new der();
• c5.add(2, 3);
• Console.ReadKey();
• }
• }
• }
Virtual Methods
• A virtual method is a method that is declared
as virtual in a base class. The characteristic of
a virtual method is that it can be redefined in
one or more derived classes. Virtual keyword
is used with method declaration.
• Virtual methods are interesting because of
what happens when one is called through a
base class reference.
Contd..
• At the run-time, C# determines which
version of the virtual method to be called
depending upon what type of object’s
reference is passed to base class object.
• Such as:
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; // a base class reference
baseRef = dob1;
baseRef.Who(); Contd..
• The syntax for virtual methods:
Modifier virtual type methodname(para)
{
…….
}
• After declaring a virtual method in base class, we
have to redefine it in the derived classes using
override keyword. Thus, the process of redefining
a virtual method inside a derived class is called
method overriding.

Contd..
Example:
• class Base
{
public virtual void Who()
{
Console.WriteLine("Who() in Base");
}
}
class Derived1 : Base
{
public override void Who()
{
Console.WriteLine("Who() in Derived1");
}
}
class Derived2 : Base
{
public override void Who()
{
Console.WriteLine("Who() in Derived2");
}
}
class OverrideDemo
{
static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; // a base class reference
baseRef = baseOb;
baseRef.Who();
baseRef = dOb1;
baseRef.Who();
baseRef = dOb2;
baseRef.Who();
}
}
• The output is:
Who() in Base
Who() in Derived1
Who() in Derived2
Sealed Classes
• C# introduce a new keyword “sealed “ which
prevent a class to be inherited further.
• Syntax is:
sealed class name
{
…….
}
Interfaces
• An interface is set methods only as a class and
structure but the behavior of methods is of
abstract type.
• Interfaces define what should be done, but
not how to do it.
• Once an interface is defined, any number of
classes can implement it. Also, one class can
implement any number of interfaces.
Contd..
• To implement an interface, a class must provide
bodies (implementations) for the methods
described by the interface.
• Declaring an interface:
modifier interface name {
ret-type method-name1(param-list);
ret-type method-name2(param-list);
ret-type method-nameN(param-list);
}
• In an interface, methods are implicitly public,
and no explicit access specifier is allowed.
Contd..
• Once interface is declared, it can be
implemented by any number of classes.
• The syntax is:
class class-name : interface-name1 ,interface-
name2,….,interface-namen
{
// class-body
}
• A class can inherit a base class and also
implement one or more interfaces. Contd..
• Implementing multiple interfaces or a class into
another class forms Multiple Inheritance.

class1 Interface1 interface2

class2
An Interface can be inherited into another interface.

contd..
• Example:
public interface Iseries
{
int GetNext(); // return next number in series
void Reset(); // restart
void SetStart(int x); // set starting value
}
class ByTwos : ISeries
{
int start;
int val;
public ByTwos()
{
start = 0;
val = 0;
}
}
• public int GetNext()
{
val += 2;
return val;
}
public void Reset()
{
val = start;
}
public void SetStart(int x)
{
start = x;
val = start;
}
}
Class demo_main
{
• ByTwos bi=new ByTwos();
int v=bi.GetNext();
bi.Reset();
bi.SetStart(2);
Console.WriteLine(v);
}
}
The output is:2
Using interface Reference
variables
• Interface reference variables can be used to
invoke particular set of version of interface
methods.
• For Example: ByTwos twoOb = new ByTwos();
ISeries ob;
ob = twoOb;
ob.GetNext();
Activity
• Implement Multiple Inheritance using interfaces.
Design class named “Data” having two variables
a,b. Accept the value using Get() method in
“Data”. Create an Interface “I1” which contain
arithmetic methods named add(),sub(),mul().
A class Action inherit both “Data”, and Interface
“I1”. Implement all methods to perform addition,
subtraction and multiplication of a and b in
“Action”.
Anonymous Types
• It is a class that has no name. Its primary use
is to store the data without knowing the type
of data. That’s why it is called anonymous.
• To declare an anonymous type “new” keyword
is used following by {…}
• Syntax is:
new {nameA=valueA,nameB=valueB,…}
Here nameA,nameB are read-only public
properties.
• Such as:
Var myobj=new{count=0,Max=100,Min=0};
Myobj is assigned reference to the object
which contian count,Max,Min properties.
so with myobj properties can be accessed.
Console.WriteLine(myobj.count);

Contd..
• Class ann_ex
{
public static void Main(strin[]args)
{
var product=new{ID=12,name=“Piano”,
price=1235};
Console.WriteLine(product.name);
}
}
• C# compiler automatically parse the
anonymous syntax. The type of each property
is determined by compiler depending upon
type of value used to initialize it.
Thank You !

Você também pode gostar