53
Inheritance in c# Lect.No-15 Date-15-04-2011

Inheritance in C#

  • Upload
    anik

  • View
    125

  • Download
    7

Embed Size (px)

DESCRIPTION

Inheritance in C#, Interfaces, abstract classes..

Citation preview

Page 1: Inheritance in C#

Inheritance in c#

Lect.No-15

Date-15-04-2011

Page 2: Inheritance in C#

Overview• Introduction• Need of Inheritance• Extending Base Classes• Accessing Base Class Data• Use of Constructor in Inheritance• Abstract Class• Virtual Methods• Anonymous Types

Page 3: Inheritance in C#

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…

Page 4: Inheritance in C#

• 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

Page 5: Inheritance in C#

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.)

Page 6: Inheritance in C#

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 ?

Page 7: Inheritance in C#

Solution is…

Page 8: Inheritance in C#

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.

Page 9: Inheritance in C#

Extending Base Class…• Syntax for deriving a class from a base

class • Class Base_class

{......

}Class Derive_class : Base_class{

....... }

Page 10: Inheritance in C#

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

Page 11: Inheritance in C#

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..

Page 12: Inheritance in C#

class derive1 : base1{

public void display(){

Console.WriteLine(“a=“+a+”b=“+b);}

}

contd…

ExtendingBase class

Page 13: Inheritance in C#

class main_class{

static void Main(string[] args){

derive1 d=new derive1();d.init();d.display();Console.ReadKey();

}}

Derive class object

Page 14: Inheritance in C#

Here is the output !

Enter a & b: 45a=4b=5

Page 15: Inheritance in C#

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

Constructors in Inheritance…

Page 16: Inheritance in C#

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…

Page 17: Inheritance in C#

• For example:public derive1(int x,int y,int z):base(x,y){

c=z;}

Base keyword

Page 18: Inheritance in C#

• class base1{

public int a,b;public base1(int x,int y){

a=x; b=y;}

}

Page 19: Inheritance in C#

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…

Page 20: Inheritance in C#

class main_class{

static void Main(string[] args){

derive1 d=new derive1(1,2,3);d.display();Console.ReadKey();

}}

Page 21: Inheritance in C#

Output is:

• a=1b=2c=3

Page 22: Inheritance in C#

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..

Page 23: Inheritance in C#

• 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..

Page 24: Inheritance in C#

• 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..

Page 25: Inheritance in C#

• 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..

Page 26: Inheritance in C#

• 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);• }• }•

Page 27: Inheritance in C#

• class main_abs• {• public static void Main(string[]

args)• {• der c5 = new der();• c5.add(2, 3);• Console.ReadKey();• }• }• }

Page 28: Inheritance in C#

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..

Page 29: Inheritance in C#

• 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 referencebaseRef = dob1;baseRef.Who(); Contd..

Page 30: Inheritance in C#

• 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..

Page 31: Inheritance in C#

Example:• class Base

{ public virtual void Who() {

Console.WriteLine("Who() in Base");

}}

Page 32: Inheritance in C#

class Derived1 : Base {

public override void Who() {Console.WriteLine("Who() in

Derived1");}

}

Page 33: Inheritance in C#

class Derived2 : Base {

public override void Who() {Console.WriteLine("Who() in

Derived2");}

}

Page 34: Inheritance in C#

class OverrideDemo {

static void Main() {Base baseOb = new Base();Derived1 dOb1 = new Derived1();Derived2 dOb2 = new Derived2();Base baseRef; // a base class referencebaseRef = baseOb;baseRef.Who();baseRef = dOb1;baseRef.Who();baseRef = dOb2;baseRef.Who();}

}

Page 35: Inheritance in C#

• The output is:Who() in BaseWho() in Derived1Who() in Derived2

Page 36: Inheritance in C#

Sealed Classes

• C# introduce a new keyword “sealed “ which prevent a class to be inherited further.

• Syntax is:sealed class name{ …….}

Page 37: Inheritance in C#

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..

Page 38: Inheritance in C#

• 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..

Page 39: Inheritance in C#

• 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..

Page 40: Inheritance in C#

• 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..

Page 41: Inheritance in C#

• Example:public interface Iseries{int GetNext(); // return next number in seriesvoid Reset(); // restartvoid SetStart(int x); // set starting value}

Page 42: Inheritance in C#

class ByTwos : ISeries {

int start;int val;public ByTwos() {start = 0;val = 0;}

}

Page 43: Inheritance in C#

• public int GetNext() {

val += 2;return val;

}public void Reset() {

val = start;}

Page 44: Inheritance in C#

public void SetStart(int x) {

start = x;val = start;

}}Class demo_main{

Page 45: Inheritance in C#

• ByTwos bi=new ByTwos();int v=bi.GetNext();bi.Reset();bi.SetStart(2);

Console.WriteLine(v);}}The output is:2

Page 46: Inheritance in C#

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

Page 47: Inheritance in C#

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”.

Page 48: Inheritance in C#

Anonymous Types

Page 49: Inheritance in C#

• 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.

Page 50: Inheritance in C#

• 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..

Page 51: Inheritance in C#

• Class ann_ex{

public static void Main(strin[]args)

{var

product=new{ID=12,name=“Piano”,price=1235};

Console.WriteLine(product.name);}

}

Page 52: Inheritance in C#

• 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.

Page 53: Inheritance in C#

Thank You !