Inheritance , Interfaces,
Abstraction and Polymorphism
Inheritance
• Inheritance allows a software developer to derive a new class from an
existing one.
• The existing class is called the parent, super, or base class.
• The derived class is called a child or subclass.
• The child inherits characteristics of the parent.
• Methods and data defined for the parent class.
• The child has special rights to the parents methods and data.
• Public access like any one else
• Protected access available only to child classes (and their
descendants).
• The child has its own unique behaviors and data.
Inheritance
• Inheritance relationships are
often shown graphically in a
class diagram, with the arrow
pointing to the parent class.
• Inheritance should create an is-a
relationship, meaning the child
is a more specific version of the
parent.
Animal
Bird
Examples: Base Classes and Derived Classes
Declaring a Derived Class
• Define a new class DerivedClass which extends BaseClass
class BaseClass
{
// class contents
}
class DerivedClass : BaseClass
{
// class contents
}
Controlling Inheritance
• A child class inherits the methods and data defined for the parent
class; however, whether a data or method member of a parent class
is accessible in the child class depends on the visibility modifier of a
member.
• Variables and methods declared with private visibility are not
accessible in the child class
• However, a private data member defined in the parent class is still
part of the state of a derived class.
• Variables and methods declared with public visibility are accessible;
but public variables violate our goal of encapsulation
• There is a third visibility modifier that helps in inheritance situations:
protected.
+ public
- private
# protected
The protected Modifier
• Variables and methods declared with
protected visibility in a parent class
are only accessible by a child class or
any class derived from that class
Book
# pages : int
+ GetNumberOfPages() : void
Dictionary
- definition : int
+ PrintDefinitionMessage() : void
Single Inheritance
• Some languages, e.g., C++, allow Multiple inheritance, which allows a
class to be derived from two or more classes, inheriting the members
of all parents.
• C# and Java support single inheritance, meaning that a derived class
can have only one parent class.
Overriding Methods
• A child class can override the definition of an inherited method in
favor of its own
• That is, a child can redefine a method that it inherits from its parent
• The new method must have the same signature as the parent's
method, but can have a different implementation.
• The type of the object executing the method determines which
version of the method is invoked.
Class Hierarchies
• A child class of one parent can be the parent of another child,
forming a class hierarchy
Animal
Reptile Bird Mammal
Snake Lizard Bat
Horse
Parrot
Initializing Base Class
• The derived class inherits the base class member variables and
member methods. Therefore the super class object should be created
before the subclass is created.
public class Person
{
protected string ssn ;
protected string name;
public Person(string s, string n)
{
ssn = s;
name = n;
}
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee : Person
{
public string id;
public Employee (string ssn,string name,string ID)
:base(ssn,name)
{
id = ID;
}
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
static void Main()
{
Employee E = new Employee("444-55-
6666","John L. Malgraine","ABC567EFG");
E.GetInfo();
Console.ReadKey();
}
}
Casting in inheritance
• An assignment of derived class object to a base class reference in C#
inheritance is known as up-casting. The up-casting is implicit and any
explicit typecast is not required.
• An assignment of base class object to derived class object is known as
Down-casting.
*
public class Shape
{
//Draw()available to base class Shape and all child
classes
public void Draw()
{
Console.WriteLine("Shape");
}
}
public class Circle : Shape
{
public new void Draw()
{
Console.WriteLine("Drawing a Circle ");
}
//Speciallized method available to only Circle class
public void write()
{
base.Draw();
Draw();
Console.WriteLine("Filling a Circle");
}
}
*
class Program
{
static void Main(string[] args)
{
Shape s = new Shape();
s.Draw();
Circle c = new Circle();
c.Draw();
Shape s1 = new Circle();//up-casting
s1.Draw();
Circle c1 = (Circle)s1; //Down-casting-casting.
c1.Draw();
Console.ReadLine();
}
}
Abstract Class
• Data Abstraction is the property by virtue of which only the essential
details are exhibited to the user. The trivial or the non-essentials units
aren’t exhibited to the user.
• The abstract keyword enables you to create classes and class members that are
incomplete and must be implemented in a derived class.
• Abstract classes cannot be instantiated.
• Class that contains the abstract keyword with some of its methods(not all
abstract method) is known as an Abstract Base Class.
• Class that contains the abstract keyword with all of its methods is known
as pure Abstract Base Class.
• You are not allowed to declare the abstract methods outside the abstract
class.
• You are not allowed to declare abstract class as Sealed Class.
• purpose of an abstract class is to provide a common definition of a base class
Abstract Method
• Abstract methods have no
implementation, so the method
definition is followed by a
semicolon instead of a normal
method block.
• Derived classes of the abstract
class must implement all abstract
methods.
• When an abstract class inherits a
virtual method from a base class,
the abstract class can override the
virtual method with an abstract
method.
Abstract Class
*
override
• The override modifier is
required to extend or
modify the abstract or
virtual implementation of
an inherited method,
property, indexer, or
event.
• You cannot override a
non-virtual or static
method. The overridden
base method must be
virtual, abstract, or
override.
INTERFACES
Interfaces are reference types. It is basically a class with the following
differences:
1. All members of an interface are explicitly PUBLIC and ABSTRACT.
2. Interface cant contain CONSTANT fields, CONSTRUCTORS and DESTRUCTORS.
3. Its members can’t be declared STATIC.
4. All the methods are ABSTRACT, hence don’t include any implementation code.
5. An Interface can inherit multiple Interfaces.
WHY INTERFACES???
C# doesn’t support MULTIPLE INHERITANCE.
A
B
C
A B
C
THIS IS POSSIBLE IN C#
THIS IS NOT POSSIBLE IN C#
• As evident from the previous diagram, in C#, a class cannot have more than one SUPERCLASS.
For example, a definition like:
Class A: B,C
{
.........
.........
}
is not permitted in C#.
• However, the designers of the language couldn’t overlook the importance of the concept of multiple inheritance.
• A large number of real life situations require the use of multiple inheritance whereby we inherit the properties of more
than one distinct classes.
•
For this reason, C# provides the concept of interfaces. Although a class can’t inherit multiple classes, it can IMPLEMENT
multiple interfaces.
INTERFACES ALLOW US TO CREATE CLASSES THAT BUILD UPON OTHER CLASSES WITHOUT THE CONFUSION CREATED BY
MULTIPLE INHERITANCE.
Implementing interfaces
An interface can contain one or multiple METHODS, PROPERTIES, INDEXERS and EVENTS. But,
these are NOT implemented in the interface itself.
They are defined in the class that implements the interface.
Syntax for defining an interface:
interface interfacename
{
member declarations..
}
DEFINING AN INTERFACE
Example:
interface Show
{
void Display(); // method within interface
int Aproperty
{
get; // property within interface
}
event someEvent Changed; // event within interface
}
EXTENDING AN INTERFACE
• Interfaces can be extended like classes. One interface can be sub interfaced from other interfaces.
Example:
interface addition
{
int add(int x, int y);
}
interface Compute: addition
{
int sub(int x, int y);
}
the above code will place both the methods, add() and sub() in the interface Compute. Any class implementing Compute will be able
to implement both these methods.
INTERFACES CAN EXTEND ONLY INTERFACES, THEY CAN’T EXTEND CLASSES.
This would violate the rule that interfaces can have only abstract members.
IMPLEMENTING INTERFACES
An Interface can be implemented as follows:
class classname: interfacename
{
body of classname
}
A class can derive from a single class and implement as many interfaces required:
class classname: superclass, interface1,interface 2,…
{
body of class name
}
eg:
class A: B,I1,I2,..
{
…….
……..
}
PROGRAM TO IMPLEMENT MULTIPLE INTERFACES
using System;
interface Addition
{
int Add();
}
interface Multiplication
{
int Mul();
}
class Compute:Addition,Multiplication
{
int x,y;
public Compute(int x, int y)
{
this.x=x;
this.y=y;
}
public int Add() //implement Add()
{
return(x+y);
}
public int Mul() //implement Mul()
{
return(x*y);
}
}
public class interfaceTest
{
public static void Main()
{
Compute com=new Compute(10,20);
Console.WriteLine(“sum is:”+com.Add());
Console.WriteLine(“product is:”+com.Mul());
}
} OUTPUT
sum is: 30
product is: 200
MULTILPLE IMPEMENTATION OF AN INTERFACE
• Just as a class can implement multiple interfaces, one single interface can be implemented
by multiple classes.
using System;
interface Area
{
double Compute(double x);
}
class Square:Area
{
public double Compute(double x)
{
return(x*x);
}
class Circle:Area
{
public double Compute(double x)
{
return(Math.PI*x*x);
}
}
Class InterfaceTest
{
public static void Main()
{
Square sqr=new Square();
Circle cir=new Circle();
Console.WriteLine(“area of square is:”+sqr.Compute(10.0));
Console.WriteLine(“area of circle is:”+cir.Compute(10.0));
}
}
OUTPUT
area of square is: 100
area of circle is: 314.159265
INTERFACES AND INHERITANCE:
We may encounter situations where the base class of a derived class implements an
interface.
when an object of the derived class is converted to the interface type, the inheritance
hierarchy is searched until it finds a class that has directly implemented the interface.
using system;
interface Display
{
void Print();
}
class B:Display //implements Display
{
public void Print()
{
Console.Writeline(“base display”);
}
}
class D:B //inherits B class
{
public new void Print()
{
Console.Writeline(“Derived display”);
}
}
class InterfaceTest3
{
public static void Main()
{
D d=new D();
d.Print();
Display dis=d;
dis.Print();
}
}
OUTPUT:
Derived display
base display
The statement dis.Print() calls the method in the base class B but not in the derived class itself.
This is because the derived class doesn’t implement the interface.
The main reason why c# doesn’t support multiple inheritance is the problem of NAME COLLISION.
But the problem still persists in C# when we are implementing multiple interfaces.
The problem is that whether the class classone implements i1.show() or i2.show()??
This is ambiguous and the compiler will report an error.
To overcome this problem we have something called EXPLICIT INTERFACE IMPLEMENTATION. This
allows us to specify the name of the interface we want to implement.
In this case don’t use “public” access specifier during implementation of show() method.
We take the following program as an example:
using system;
interface i1
{
void show();
}
interface i2
{
void show();
}
EXPLICIT INTERFACE IMPLEMENTATION
class classone: i1,i2
{
void i1.show()
{
Console.WriteLine(“ implementing i1”);
}
void i2.show()
{
Console.WriteLine(“ implementing i2”);
}
}
class interfaceImplement
{
public static void Main()
{
classone c1=new classone();
i1 x=c1;
x.show();
i2 y=c1;
y.show();
}
}
OUTPUT:
implementing i1
implementing i2
Polymorphism
*
• "Polymorphism" ="poly" + "morphs" which means
many forms. It is a greek word.
• types of polymorphism in C#
• compile time polymorphism -method overloading and
operator overloading
• and runtime polymorphism-method overriding
*
Virtual Methods
• By declaring a base class function as virtual, we allow the function to
be overridden in any derived classes:
class MyBaseClass
{
public virtual string VirtualMethod()
{
return “This method defined in MyBaseClass”;
}
}
• It is also permitted to declare a property as virtual.
• For a virtual or overridden property, the syntax is the same as for a non-virtual
property with the exception of the keyword virtual, which is added to the definition.
• The syntax looks like this:
public virtual string ForeName
{
get { return foreName;}
set { foreName = value;}
}
private string foreName;
• In Java, by contrast, all functions are virtual.
• it requires you to declare when a derived class’s function overrides another function,
using the override keyword:
class MyDerivedClass : MyBaseClass
{
public override string VirtualMethod()
{
return “This is an override method defined in MyDerivedClass”;
}
}
Neither member fields nor static functions can be declared as virtual.
Hiding Methods
• If a method with the same signature
is declared in both base and derived
classes, but the methods are not
declared as virtual and override
respectively, then the derived class
version is said to hidden by the base
class version.
• The warning caused by hiding an
inherited name can be eliminated
through use of the new modifier
• The new modifier indicates that the F
in Derived is "new", and that it is
indeed intended to hide the inherited
member.
Overloading vs. Overriding
• Overloading deals with
multiple methods in the
same class with the same
name but different
signatures
• Overloading lets you define a
similar operation in different
ways for different data
• Example:
int foo(string[] bar);
int foo(int bar1, float a);
• Overriding deals with two
methods, one in a parent
class and one in a child
class, that have the same
signature
• Overriding lets you define a
similar operation in
different ways for different
object types
• Example:
class Base {
public virtual int foo() {} }
class Derived {
public override int foo() {}}
Operator Overloading
The comparison operators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, !=
must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.
Extension Methods
• Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type.
• Extension methods are a special kind of static method, but they are
called as if they were instance methods on the extended type.
• An extension method is a static method to the existing static class.
• We call an extension method in the same general way; there is no
difference in calling.
• If you create extension methods that have the same signature
methods as the type you are extending, then the extension methods
will never be called.
Defining a Extension method for int type
• Their first parameter specifies which type the method operates on, and the
parameter is preceded by the this modifier.
• Extension methods are only in scope when you explicitly import the namespace into
your source code with a using directive.
namespace ExtensionMethods
{
public static class IntExtensions
{
public static bool IsGreaterThan(this int i, int value)
{
return i > value;
}
}
}
Using Extension methods
using ExtensionMethods;
class Program
{
static void Main(string[] args)
{
int i = 10;
bool result = i.IsGreaterThan(100);
Console.WriteLine(result);
}
}
Inheritance.pptx

Inheritance.pptx

  • 1.
  • 2.
    Inheritance • Inheritance allowsa software developer to derive a new class from an existing one. • The existing class is called the parent, super, or base class. • The derived class is called a child or subclass. • The child inherits characteristics of the parent. • Methods and data defined for the parent class. • The child has special rights to the parents methods and data. • Public access like any one else • Protected access available only to child classes (and their descendants). • The child has its own unique behaviors and data.
  • 3.
    Inheritance • Inheritance relationshipsare often shown graphically in a class diagram, with the arrow pointing to the parent class. • Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent. Animal Bird
  • 4.
    Examples: Base Classesand Derived Classes
  • 5.
    Declaring a DerivedClass • Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents }
  • 6.
    Controlling Inheritance • Achild class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member. • Variables and methods declared with private visibility are not accessible in the child class • However, a private data member defined in the parent class is still part of the state of a derived class. • Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation • There is a third visibility modifier that helps in inheritance situations: protected.
  • 7.
    + public - private #protected The protected Modifier • Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class Book # pages : int + GetNumberOfPages() : void Dictionary - definition : int + PrintDefinitionMessage() : void
  • 8.
    Single Inheritance • Somelanguages, e.g., C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents. • C# and Java support single inheritance, meaning that a derived class can have only one parent class.
  • 9.
    Overriding Methods • Achild class can override the definition of an inherited method in favor of its own • That is, a child can redefine a method that it inherits from its parent • The new method must have the same signature as the parent's method, but can have a different implementation. • The type of the object executing the method determines which version of the method is invoked.
  • 10.
    Class Hierarchies • Achild class of one parent can be the parent of another child, forming a class hierarchy Animal Reptile Bird Mammal Snake Lizard Bat Horse Parrot
  • 11.
    Initializing Base Class •The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created.
  • 14.
    public class Person { protectedstring ssn ; protected string name; public Person(string s, string n) { ssn = s; name = n; } public virtual void GetInfo() { Console.WriteLine("Name: {0}", name); Console.WriteLine("SSN: {0}", ssn); } } class Employee : Person { public string id; public Employee (string ssn,string name,string ID) :base(ssn,name) { id = ID; } public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); Console.WriteLine("Employee ID: {0}", id); } } class TestClass { static void Main() { Employee E = new Employee("444-55- 6666","John L. Malgraine","ABC567EFG"); E.GetInfo(); Console.ReadKey(); } }
  • 15.
    Casting in inheritance •An assignment of derived class object to a base class reference in C# inheritance is known as up-casting. The up-casting is implicit and any explicit typecast is not required. • An assignment of base class object to derived class object is known as Down-casting. *
  • 16.
    public class Shape { //Draw()availableto base class Shape and all child classes public void Draw() { Console.WriteLine("Shape"); } } public class Circle : Shape { public new void Draw() { Console.WriteLine("Drawing a Circle "); } //Speciallized method available to only Circle class public void write() { base.Draw(); Draw(); Console.WriteLine("Filling a Circle"); } } * class Program { static void Main(string[] args) { Shape s = new Shape(); s.Draw(); Circle c = new Circle(); c.Draw(); Shape s1 = new Circle();//up-casting s1.Draw(); Circle c1 = (Circle)s1; //Down-casting-casting. c1.Draw(); Console.ReadLine(); } }
  • 17.
    Abstract Class • DataAbstraction is the property by virtue of which only the essential details are exhibited to the user. The trivial or the non-essentials units aren’t exhibited to the user. • The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. • Abstract classes cannot be instantiated. • Class that contains the abstract keyword with some of its methods(not all abstract method) is known as an Abstract Base Class. • Class that contains the abstract keyword with all of its methods is known as pure Abstract Base Class. • You are not allowed to declare the abstract methods outside the abstract class. • You are not allowed to declare abstract class as Sealed Class. • purpose of an abstract class is to provide a common definition of a base class
  • 18.
    Abstract Method • Abstractmethods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. • Derived classes of the abstract class must implement all abstract methods. • When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.
  • 19.
  • 20.
    override • The overridemodifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. • You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
  • 21.
    INTERFACES Interfaces are referencetypes. It is basically a class with the following differences: 1. All members of an interface are explicitly PUBLIC and ABSTRACT. 2. Interface cant contain CONSTANT fields, CONSTRUCTORS and DESTRUCTORS. 3. Its members can’t be declared STATIC. 4. All the methods are ABSTRACT, hence don’t include any implementation code. 5. An Interface can inherit multiple Interfaces.
  • 22.
    WHY INTERFACES??? C# doesn’tsupport MULTIPLE INHERITANCE. A B C A B C THIS IS POSSIBLE IN C# THIS IS NOT POSSIBLE IN C#
  • 23.
    • As evidentfrom the previous diagram, in C#, a class cannot have more than one SUPERCLASS. For example, a definition like: Class A: B,C { ......... ......... } is not permitted in C#. • However, the designers of the language couldn’t overlook the importance of the concept of multiple inheritance. • A large number of real life situations require the use of multiple inheritance whereby we inherit the properties of more than one distinct classes. • For this reason, C# provides the concept of interfaces. Although a class can’t inherit multiple classes, it can IMPLEMENT multiple interfaces. INTERFACES ALLOW US TO CREATE CLASSES THAT BUILD UPON OTHER CLASSES WITHOUT THE CONFUSION CREATED BY MULTIPLE INHERITANCE.
  • 24.
    Implementing interfaces An interfacecan contain one or multiple METHODS, PROPERTIES, INDEXERS and EVENTS. But, these are NOT implemented in the interface itself. They are defined in the class that implements the interface. Syntax for defining an interface: interface interfacename { member declarations.. } DEFINING AN INTERFACE Example: interface Show { void Display(); // method within interface int Aproperty { get; // property within interface } event someEvent Changed; // event within interface }
  • 25.
    EXTENDING AN INTERFACE •Interfaces can be extended like classes. One interface can be sub interfaced from other interfaces. Example: interface addition { int add(int x, int y); } interface Compute: addition { int sub(int x, int y); } the above code will place both the methods, add() and sub() in the interface Compute. Any class implementing Compute will be able to implement both these methods. INTERFACES CAN EXTEND ONLY INTERFACES, THEY CAN’T EXTEND CLASSES. This would violate the rule that interfaces can have only abstract members.
  • 26.
    IMPLEMENTING INTERFACES An Interfacecan be implemented as follows: class classname: interfacename { body of classname } A class can derive from a single class and implement as many interfaces required: class classname: superclass, interface1,interface 2,… { body of class name } eg: class A: B,I1,I2,.. { ……. …….. }
  • 27.
    PROGRAM TO IMPLEMENTMULTIPLE INTERFACES using System; interface Addition { int Add(); } interface Multiplication { int Mul(); } class Compute:Addition,Multiplication { int x,y; public Compute(int x, int y) { this.x=x; this.y=y; }
  • 28.
    public int Add()//implement Add() { return(x+y); } public int Mul() //implement Mul() { return(x*y); } } public class interfaceTest { public static void Main() { Compute com=new Compute(10,20); Console.WriteLine(“sum is:”+com.Add()); Console.WriteLine(“product is:”+com.Mul()); } } OUTPUT sum is: 30 product is: 200
  • 29.
    MULTILPLE IMPEMENTATION OFAN INTERFACE • Just as a class can implement multiple interfaces, one single interface can be implemented by multiple classes. using System; interface Area { double Compute(double x); } class Square:Area { public double Compute(double x) { return(x*x); } class Circle:Area { public double Compute(double x) { return(Math.PI*x*x); } }
  • 30.
    Class InterfaceTest { public staticvoid Main() { Square sqr=new Square(); Circle cir=new Circle(); Console.WriteLine(“area of square is:”+sqr.Compute(10.0)); Console.WriteLine(“area of circle is:”+cir.Compute(10.0)); } } OUTPUT area of square is: 100 area of circle is: 314.159265
  • 31.
    INTERFACES AND INHERITANCE: Wemay encounter situations where the base class of a derived class implements an interface. when an object of the derived class is converted to the interface type, the inheritance hierarchy is searched until it finds a class that has directly implemented the interface. using system; interface Display { void Print(); } class B:Display //implements Display { public void Print() { Console.Writeline(“base display”); } }
  • 32.
    class D:B //inheritsB class { public new void Print() { Console.Writeline(“Derived display”); } } class InterfaceTest3 { public static void Main() { D d=new D(); d.Print(); Display dis=d; dis.Print(); } } OUTPUT: Derived display base display The statement dis.Print() calls the method in the base class B but not in the derived class itself. This is because the derived class doesn’t implement the interface.
  • 33.
    The main reasonwhy c# doesn’t support multiple inheritance is the problem of NAME COLLISION. But the problem still persists in C# when we are implementing multiple interfaces. The problem is that whether the class classone implements i1.show() or i2.show()?? This is ambiguous and the compiler will report an error. To overcome this problem we have something called EXPLICIT INTERFACE IMPLEMENTATION. This allows us to specify the name of the interface we want to implement. In this case don’t use “public” access specifier during implementation of show() method. We take the following program as an example: using system; interface i1 { void show(); } interface i2 { void show(); } EXPLICIT INTERFACE IMPLEMENTATION
  • 34.
    class classone: i1,i2 { voidi1.show() { Console.WriteLine(“ implementing i1”); } void i2.show() { Console.WriteLine(“ implementing i2”); } } class interfaceImplement { public static void Main() { classone c1=new classone(); i1 x=c1; x.show(); i2 y=c1; y.show(); } } OUTPUT: implementing i1 implementing i2
  • 35.
  • 36.
    • "Polymorphism" ="poly"+ "morphs" which means many forms. It is a greek word. • types of polymorphism in C# • compile time polymorphism -method overloading and operator overloading • and runtime polymorphism-method overriding *
  • 37.
    Virtual Methods • Bydeclaring a base class function as virtual, we allow the function to be overridden in any derived classes: class MyBaseClass { public virtual string VirtualMethod() { return “This method defined in MyBaseClass”; } }
  • 38.
    • It isalso permitted to declare a property as virtual. • For a virtual or overridden property, the syntax is the same as for a non-virtual property with the exception of the keyword virtual, which is added to the definition. • The syntax looks like this: public virtual string ForeName { get { return foreName;} set { foreName = value;} } private string foreName;
  • 39.
    • In Java,by contrast, all functions are virtual. • it requires you to declare when a derived class’s function overrides another function, using the override keyword: class MyDerivedClass : MyBaseClass { public override string VirtualMethod() { return “This is an override method defined in MyDerivedClass”; } } Neither member fields nor static functions can be declared as virtual.
  • 40.
    Hiding Methods • Ifa method with the same signature is declared in both base and derived classes, but the methods are not declared as virtual and override respectively, then the derived class version is said to hidden by the base class version. • The warning caused by hiding an inherited name can be eliminated through use of the new modifier • The new modifier indicates that the F in Derived is "new", and that it is indeed intended to hide the inherited member.
  • 41.
    Overloading vs. Overriding •Overloading deals with multiple methods in the same class with the same name but different signatures • Overloading lets you define a similar operation in different ways for different data • Example: int foo(string[] bar); int foo(int bar1, float a); • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature • Overriding lets you define a similar operation in different ways for different object types • Example: class Base { public virtual int foo() {} } class Derived { public override int foo() {}}
  • 42.
    Operator Overloading The comparisonoperators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, != must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.
  • 44.
    Extension Methods • Extensionmethods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. • Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. • An extension method is a static method to the existing static class. • We call an extension method in the same general way; there is no difference in calling. • If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.
  • 45.
    Defining a Extensionmethod for int type • Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. • Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. namespace ExtensionMethods { public static class IntExtensions { public static bool IsGreaterThan(this int i, int value) { return i > value; } } }
  • 46.
    Using Extension methods usingExtensionMethods; class Program { static void Main(string[] args) { int i = 10; bool result = i.IsGreaterThan(100); Console.WriteLine(result); } }