Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
60 views

Session 4 CSharp Inheritance Polymorphism Interfaces AbstractClass

The document discusses object-oriented programming concepts like inheritance, polymorphism, interfaces, and abstract classes. It covers inheritance in detail including classical inheritance, containment inheritance, extending base classes, and accessing base class members. The document also discusses access modifiers, class visibility, class member visibility, and inheritance examples.

Uploaded by

NoFear NoTear
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Session 4 CSharp Inheritance Polymorphism Interfaces AbstractClass

The document discusses object-oriented programming concepts like inheritance, polymorphism, interfaces, and abstract classes. It covers inheritance in detail including classical inheritance, containment inheritance, extending base classes, and accessing base class members. The document also discusses access modifiers, class visibility, class member visibility, and inheritance examples.

Uploaded by

NoFear NoTear
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 79

Session 4

Inheritance, Polymorphism,
Interfaces, Abstract Class

1
Contents

 Inheritance
 Polymorphism
 Interfaces
 Abstract Classes

2
Inheritance

3
Inheritance
 Inheritance  Virtual Methods
 Classical Inheritance  Overriding Methods
 Containment Inheritance  Hiding Methods
 Extension Base Classes  Sealed Class
 Access Modifiers
 Class Visibility
 Class Members Visibility
 Accessibility Constraints
4
Inheritance
 Reusability
 The mechanism of designing or constructing one class
from another is called inheritance.
 Two different forms in inheritance
 Classical inheritance
 Containment inheritance
A class can only inherit from one base class, but it can
implement multiple interfaces.
 A class can only inherit from a class, not from a struct.
 Structs cannot inherit from another type, but they can
implement multiple interfaces.
5
Classical Inheritance
 A kind of relationship between two classes
 Base class or parent class or super class
 Derived class or child class or sub class
 is-a relationship
Class A Base class

Derived class
Class B
6
Classical Inheritance
 Single Inheritance
 Multiple Inheritance (C# does not support)
 Hierarchical Inheritance
 Multilevel Inheritance

7
Containment Inheritance
class A
{ Car Object
…..
} Radio Object
class B
{
….
A a; // a is contained in b
}

8
Extending Base Classes
 Syntax for deriving a class from a base class
 A derived class inherits most elements of its base
class
 A derived class cannot be more accessible than
its base class
class
class Token
Token
{{ Derived
Token
Token
Derivedclass
class
...
... Base
Baseclass
class «« concrete
concrete »»
}}
class
class CommentToken:
CommentToken: Token Token
{{
... CommentToken
CommentToken
... «« concrete
}} Colon concrete »»
Colon 9
Accessing Base Class Members
class
class Token
Token
{{ ...
... class
class Outside
Outside
protected
protected string
string name;
name; {{
}} void
void Fails(Token
Fails(Token t)
t)
class
class CommentToken:
CommentToken: Token
Token {{


{{ ...
... ...
...
public
public string
string Name(
Name( )) t.name
t.name
{{ ...
...

}}
return
return name;
name;  }}
}}

}}

 Inherited protected members are implicitly protected


in the derived class
 Methods of a derived class can access only their
inherited protected members
 Protected access modifiers cannot be used in a struct
10
Calling Base Class Constructors
 Constructor declarations must use the base keyword
 A private base class constructor cannot be accessed by
a derived class
 Use the base keyword to qualify identifier scope

class
class Token
Token
{{
protected
protected Token(string
Token(string name)
name) {{ ...
... }}
...
...
}}
class
class CommentToken:
CommentToken: Token
Token
{{
public
public CommentToken(string
CommentToken(string name)
name) :: base(name)
base(name) {{ }}
...
...
}}

11
Access Modifiers
 Access modifiers are keywords used to specify the
declared accessibility of a member or a type
 public: Access is not restricted.
 protected: Access is limited to the containing class or
types derived from the containing class.
 Internal: Access is limited to the current assembly.
 protected internal: Access is limited to the current
assembly or types derived from the containing class.
 private: Access is limited to the containing type.
12
Access Modifiers
Members Default member Allowed declared accessibility
of accessibility of the member
enum public None
public
protected
class private internal
private
protected internal
interface public None
public
struct private internal
private

13
Class Visibility
 To specify its level of visibility
 Two visibility modifiers : public and internal
 default : internal
 Internal classes are accessible within the same program
assembly and are not accessible from outside the assembly
 Public classes are accessible everywhere

14
Class Members Visibility
Keyword Visibility

Containing Derived Containing Anywhere


Classes Classes Program outside the
containing
program
private Y

protected Y Y

internal Y Y

protected internal Y Y Y

public Y Y Y Y

15
Class Members Visibility
using System;
namespace Session4_I public static void Main()
{ { B obj=new B ();
class A obj .Display ();
{ Console.Read();
private int x=2; }
protected int y=3; }}
public int z=4;
internal int k=5; Output:
protected internal int j=6; protected number = 3
} public number = 4
class B: A internal number = 5
{ protected internal number = 6
public void Display()
{
//Console .WriteLine ("private number = "+x);
Console .WriteLine ("protected number = "+y);
Console .WriteLine ("public number = "+z);
Console .WriteLine (“internal number = "+k);
Console .WriteLine ("protected internal number =
“+j); 16
}
Inheritance Example -1
using System; class D : B
{ int k;
public void setk()
namespace MemberAccess {
{ k = i * j;
class B }
{ public void showk()
protected int i, j; { Console.WriteLine(k);
public void set(int a, int b) }
{ }
i = a; class Access2
{ public static void Main()
j = b;
{
} D obj = new D();
public void show() obj.set(4,5);
{ obj.show();
Console.WriteLine(i + " " + j); obj.setk (); Output:
} obj .showk (); 45
} Console.Read(); 20 17
Inheritance Example-2
using System; public double Height
{ get { return height; }
namespace InheritancesEgs set { height = value; }
{ }
class TwoDShape public void showDim()
{ protected double width;// protected { Console.WriteLine("Width and height are "
protected double height;//protected + width + " and " + height);
// constructor } }
public TwoDShape(double w, double h) class Triangle : TwoDShape
{ {
width = w; public string style;
height = h; public Triangle(string s, double w, double h) :
} base(w,h)
public double Width {
{ style = s;
get { return width; } }
set { width = value; } public double Area()
} {
18
return width * height / 2; }
Inheritance Example-2
class CallBaseConstructor
{
public static void Main()
{
Triangle t1 = new Triangle("isosceles ", 12.0, 12.0);
t1.showDim();
Console.WriteLine("Area is " + t1.Area());
Console.Read();
}
}

Output:
Width and height are 12 and 12
Area is 72
19
Accessibility Constraints
 Direct base class of a derived class must be at least as
accessible as the derived class itself
 Accessibility domain of a member is never larger than
that of the class containing it
 The return type of method must be at least as accessible as
the method itself.

20
Accessibility Constraints (Cont.)
Illegal-1
class A A is internal
{

}
public class B : A
{
B is public

}
class A should be at least as accessible as class B21
Accessibility Constraints (Cont.)
Illegal-2
class A class B is
private
{
private class B
{
public int x;
… x is public accessible var
}

Variable x should be reduced to private. 22


Accessibility Constraints (Cont.)
Illegal-3
class A A is internal
{… }
public class B : A Return type of a method must
{ be at least as accessible as the
A method_1() {} //ok method itself.
internal A method_2(){} //ok
public A method_3() {} // error
} method_3 is
public 23
Virtual Methods

 A method that is declared as virtual in a base


class and redefined in one or more derived
classes
 Each derived class can have its own version of
a virtual method
 To use virtual methods:
- Cannot declare virtual methods as static, private
and abstract

24
Defining Virtual Methods
• Syntax: Declare as virtual
• Virtual methods are polymorphic

class
class Token
Token
{{
...
...
public
public int
int LineNumber(
LineNumber( ))
{{ ...
...
}}
public
public virtual
virtual string
string Name(
Name( ))
{{ ...
...
}}
}}
25
Virtual Methods
using System;
namespace VirtualDemo Output:
{
class Test Virtual method
{
public virtual void Display()
{
Console.WriteLine("Virtual method ");
}
static void Main(string[] args)
{
Test obj = new Test();

obj.Display();
}
}
26
Overriding Methods
 The override modifier is required to extend or
modify the abstract or virtual implementation of
an inherited method, property, indexer, or event.
 An override method provides a new
implementation of a member that is inherited
from a base class.
 The overridden base method must have the same
signature as the override method.

27
Overriding Methods
 Cannot override a non-virtual or static method.
 The overridden base method must be virtual, abstract,
or override.
 An override declaration cannot change the
accessibility of the virtual method.
 Both the override method and the virtual method must
have the same access level modifier.
 Cannot use the new, static, virtual, or abstract
modifiers to modify an override method.
28
Overriding Methods

 Syntax: Use the override keyword

class
class Token
Token
{{ ...
...
public
public virtual
virtual string
string Name(
Name( )) {{ ...
... }}
}}
class
class CommentToken:
CommentToken: Token
Token
{{ ...
...
public
public override
override string
string Name(
Name( )) {{ ...
... }}
}}

29
Override Methods (Cont.)
 You can only override identical inherited virtual methods
 You must match an override method with its associated virtual
method
 You can override an override method
 You cannot explicitly declare an override method as virtual
 You cannot declare an override method as static or private
class
class Token
Token
{{ ...
...
public
public int
int LineNumber(
LineNumber( )) {{ ...
... }}
public
public virtual
virtual string
string Name(
Name( )) {{ ...
... }}
}}
class
class CommentToken:
CommentToken: Token
Token
{{ ...

...
public
public override
override int
int LineNumber(
LineNumber( )) {{ ...
... }}

}}
public
public override
override string
string Name(
Name( )) {{ ...
... }} 
30
Overriding Methods
using System; class Test
{ static void Main(string[] args)
namespace VirtualAndOverride { A a;
{ class A B b;
{ public virtual void Foo() a = new A();
b = new B();
{ Console.WriteLine("A::Foo()"); } a.Foo();
} b.Foo();
class B : A a = new B();
{ public override void Foo() a.Foo(); Output:
Console.Read();
{ Console.WriteLine("B::Foo()"); } } A::Foo()
} } } B::Foo()
B::Foo()

31
Hiding Methods
 Like function overriding feature in C++
 Functions of base class are available to the derived class
 Can define its own version of the same method with the
same method signature and differing in implementation.
 This new definition hides the base class’s
– constant, field, property, event, or type introduced in a
class or struct hides all base class members with the same
name.

32
Hiding Methods
 Syntax: Use the new keyword to hide a method

class
class Token
Token
{{ ...
...
public
public int
int LineNumber(
LineNumber( )) {{ ...
... }}
}}
class
class CommentToken:
CommentToken: Token
Token
{{ ...
...
new
new public
public int
int LineNumber(
LineNumber( )) {{ ...
... }}

}}

33
Hiding Methods (Cont.)
 Hide both virtual and non-virtual methods
 Resolve name clashes in code
 Hide methods that have identical signatures

class
class Token
Token
{{ ...
...
public
public int
int LineNumber(
LineNumber( )) {{ ...
... }}
public
public virtual
virtual string
string Name(
Name( )) {{ ...
... }}
}}
class
class CommentToken:
CommentToken: Token
Token
{{ ...
...
new
new public
public int
int LineNumber(
LineNumber( )) {{ ...... }}
public
public override
override string
string Name(
Name( )) {{ ...
... }}
}}

34
Hiding Non-Virtual Methods
using System; class Program
namespace MethodHiding { static void Main(string[] args)
{ class A { B obj = new B(1, 2);
{ public int i = 0; A obj2 = new A();
public void Show() obj.Show();
{ Console.WriteLine("i in base //obj2.Show();
class: " + i); } obj2 = new B(6, 7);
} obj2.Show();
class B : A Console.Read(); }
{ new int i; }}
public B(int a, int b)
{ base.i = a;
i = b; } Output:
public new void Show()
{ base.Show(); i in base class 1
Console.WriteLine("i in derived i in derived class 2
class: " + i in base class 6 35
i); }
Hiding Virtual Methods
using System; class Test
namespace VirtualHiding { static void Main()
{ class A { D d = new D();
{ public virtual void F() A a = d;
{ Console.WriteLine("A.F"); } B b = d;
} C c = d;
class B : A a.F();
{ public override void F() b.F();
{ Console.WriteLine("B.F"); } c.F();
} d.F();
class C : B Console.Read();
{ new public virtual void F() }
{ Console.WriteLine("C.F"); } } } Output:
}
B.F
class D : C
B.F
{ public override void F()
D.F
{ Console.WriteLine("D.F"); } 36
D.F
}
Member Hiding
using System;
class Program
namespace MemberHiding
{ static void Main(string[] args)
{ class A
{ B obj = new B(10);
{ public int i = 0;
obj.show();
}
A obj1 = new A();
class B : A
Console.WriteLine(obj1.i);
{ new int i;
Console.Read();
public B(int b)
}
{ i = b; }
} }
// using base to access a hidden name
public B(int a,int b)
{ base.i = a;
Output:
i = b; }
public void show()
i in base class 0
{ Console.WriteLine("i in base
i in derived class 10
class " + base.i);
0
Console.WriteLine("i in derived
37
class " + i); }
Sealed Classes
 A sealed class is one that cannot be used as a base
class
 Sealed classes can’t be abstract
 All structs are implicitly sealed
 Why seal a class?
 To prevent unintended derivation
 Code optimization
 Virtual function calls can be resolved at
compile-time
38
Using Sealed Classes
• You cannot derive from a sealed class
• You can use sealed classes for optimizing
operations at run time
• Many .NET Framework classes are sealed:
String, StringBuilder, and so on
• Syntax: Use the sealed keyword
namespace
namespace System
System
{{
public
public sealed
sealed class
class String
String
{{
...
...
}}
}}
namespace
namespace Mine
Mine
{{
}}
class
class FancyString:
FancyString: String
String {{ ...
... }}
 39
Polymorphism

40
Polymorphism
 Polymorphism
 Compile time polymorphism (Early Binding)
 Run time polymorphism (Late Binding)
 Interface Polymorphism
 Inheritance Polymorphism
 Casting between types

41
Polymorphism
 Polymorphism means one name, many forms
 The term polymorphism (from the Greek meaning
"having multiple forms") in OO is the characteristic of
being able to assign a different meaning or usage to
something in different contexts - specifically, to allow a
variable to refer to more than one type of object.
 The capability of one object to behave in multiple
ways
42
Polymorphism

 Through inheritance, it can be used as more than one


type; it can be used as class its own type, any base types,
or any interface type if it implements interfaces
 The ability of different objects to expose different
implementations of the same public interface.
 Two major types of polymorphism in C#
 Compile time polymorphism (Early Binding)
 Run time polymorphism (Late Binding)
43
Polymorphism (Cont.)

Polymorphism

Operation Inclusion
Polymorphism Polymorphism
(using (using virtual
overloaded methods)
methods)

44
Operation Polymorphism
 Compile time polymorphism
 Using overloaded methods and operators
 Overloaded methods are selected for invoking by
matching arguments, in terms of number, type and order.
This information is known to the compiler at the time of
compilation.
 Compiler is able to select and bind the appropriate
method to the object from a particular call at compile time
itself.
 Early binding

45
Inclusion Polymorphism
 Runtime polymorphism
 Use of virtual functions
 The decision on exactly which method to call is delayed
until runtime
 Since the method is linked with a particular class much
later after compilation, the process is called late binding
or dynamic binding

46
Polymorphism in Components
 Polymorphism is the ability for classes to provide
different implementations of methods that are called by the
same name.
 Polymorphism allows a method of a class to be called
without regard to what specific implementation it provides
 Can be implemented in a variety of ways:
 Interface polymorphism
 Inheritance polymorphism
 Polymorphism through abstract classes

47
Interface Polymorphism
 An interface defines a contract for behavior
 It specifies what members must be implemented but
provides no default as to their implementation
 An object can implement many undeclared interfaces,
and many diverse objects can implement the same
interface.

48
Interface Polymorphism (Cont.)
 Multiple classes may implement the same interface,
and a single class may implement one or more interfaces.
 An interface describes the methods, properties, and
events that a class needs to implement, and the type of
parameters each member needs to receive and return, but
leaves the specific implementation of these members up
to the implementing class.

49
Inheritance Polymorphism

 Objects can inherit functionality from one another


 An inherited class retains the full implementation of its
base class and instances of inherited classes can be treated
as instances of the base class.
 Inherited classes can implement additional
functionality as required.

50
Casting Between Types
 Two types of casting
 Upcasting
 Converts an object of a specialized type to a more
general type OR
 Converts an object of a derived class to an object of
its base class
 Downcasting
 Converts an object from a general type to a more
specialized type
 Converts an object of a base class to an object of its
derived classes
51
Casting Between Types (Cont.)

class Base{ }
class Derived : Base { }

Base b = new Derived () : // OK , upcasting


Derived d = new Base () : // Error, downcasting

- C# cannot be permitted implicitly an object of a base class


to an object of its derived classes

- Downcasting is required an explicit cast operation


52
Casting Between Types : Example
class UpDownd_Cast
class Base {
{ public static void Main()
public Base() { } { Base b = new MyDerived(); // Upcasting ,
public virtual void display() // implicitly ok
{ Console.WriteLine(" Base : Display b.Test(); // Base : Test
"); } MyDerived md = new MyDerived();
public void Test() md.Test(); // MyDerived : Test
{ Console.WriteLine(" Base : Test "); } b.display(); // MyDerived : Display ,
} //override
class MyDerived : Base md.display(); // MyDerived : Display
{ //MyDerived md2 = new Base();
public MyDerived() { } // Downcasting, implicitly , Error
public override void display() Base b2 = new MyDerived();
{ Console.WriteLine(" MyDerived : Display // Downcasting, explicitly, Ok
"); } MyDerived md3 = (MyDerived)b2;
public void Test() md3.Test(); // MyDerived : Test
{ Console.WriteLine(" MyDerived : Test "); } b2.Test(); // Base : Test
} }} 53
Casting Between Types : Example

Output:

Base : Test
MyDerived : Test
MyDerived : Display
MyDerived : Display
MyDerived : Test
Base : Test

54
Polymorphism : Example
using System;    // Properties for width, height, and name 
class Shape {     public double width 
  double pri_width;  // private  {  get { return pri_width; } 
  double pri_height; // private      set { pri_width = value; }  }  
  public string  name;      public double height 
  public Shape()  {  get { return pri_height; } 
{  width = height = 0.0;       set { pri_height = value; }   } 
    name = "null";  }       public string name 
  public Shape(double w, double h, string n {  get { return pri_name; } 
)     set { pri_name = value; }   }   
{  width = w;     public void showDim() 
    height = h;   {  Console.WriteLine("Width and height are " 
    name = n;    }     +  width + " and " + height);    }   
  public Shape(double x, string n)    public virtual double area() 
{  width = height = x;   { Console.WriteLine("area() must
    name = n;    }     overridden");  
  public Shape(Shape ob)      return 0.0;  
{  width = ob.width;     }
    height = ob.height;   }   55
Polymorphism : Example
class Triangle : Shape {   class Rectangle : Shape {   
  string style; // private        public Rectangle(double w, double h) : base
  public Triangle()  (w, h, "rectangle")
{   style = "null";    }     { }    
  public Triangle(string s, double w, double h)    public Rectangle(double x) : base(x, "rectan
:     base(w, h, "triangle")  gle") 
{    style = s;     }     { }    
  public Triangle(double x) : base(x, "triangle“   // Construct an object from an object.  
)   public Rectangle(Rectangle ob) : base(ob) 
{   style = "isosceles";     }     { }    
  public Triangle(Triangle ob) : base(ob)    // Return true if the rectangle is square. 
{    style = ob.style;    }       public bool isSquare() 
  // Override area() for Triangle.  {   if(width == height) return true;   
  public override double area()      return false;     }   
{   return width * height / 2;    }       // Override area() for Rectangle. 
  // Display a triangle's style.    public override double area() 
  public void showStyle()  {       return width * height;     }   
{  Console.WriteLine("Triangle is " + style);}  }  56
         
Polymorphism : Example
class DynShapes {   Output:
  public static void Main() {   object is triangle
    Shape[] shapes = new Shape[5];    Area is 48
    shapes[0] = new Triangle("right", 8.0, 12.0);  
    shapes[1] = new Rectangle(10);   object is rectangle
    shapes[2] = new Rectangle(10, 4);   Area is 100
    shapes[3] = new Triangle(7.0);  
    shapes[4] = new Shape(10, 20, "generic");    object is rectangle
    for(int i=0; i < shapes.Length; i++)  Area is 40
{  
 Console.WriteLine("object is " + shapes[i].name object is triangle
);   Area is 24.5
      Console.WriteLine("Area is " + shapes[i].are
a());     object is generic
      Console.WriteLine();     area() must be overridden
    }    }  } Area is 0
57
Interfaces

58
Interfaces

 Declaring Interfaces
 Implementing Multiple Interfaces
 Implementing Interface Methods
 Implementing Interface Methods Explicitly

59
Interfaces
 An alternate approach supports the concept of Multiple
inheritance
 An interface can inherit multiple interfaces
 A reference type
 All members of an interface are implicitly public and
abstract.
 An interface cannot contain constant fields,
constructors and destructors
 Its members cannot be declared static 60
Interfaces (Cont.)
 An interface defines a contract
 An interface is a type
 Includes methods, properties, indexers, events
 Any class or struct implementing an interface must support
all parts of the contract
 Interfaces provide no implementation
 When a class or struct implements an interface it must
provide the implementation
 Interfaces provide polymorphism
 Many classes and structs may implement
a particular interface

61
Declaring Interfaces
Syntax: Use the interface keyword to declare

Interface
Interfacenames
namesshould
should
begin
beginwith
withaacapital
capital“I”
“I”

interface
interface IToken
IToken IToken
IToken
{{
«« interface
interface »»
int
int LineNumber(
LineNumber( );
);
string LineNumber(
LineNumber( ))
string Name(
Name( );
);
}} Name(
Name( ))

No
Noaccess
accessspecifiers
specifiers No
Nomethod
method bodies
bodies

62
Multiple Interfaces
interface
interface IToken
IToken
{{ IToken
IToken IVisitable
IVisitable
string
string Name(
Name( ); «« interface
}}
); interface »» «« interface
interface »»
interface
interface IVisitable
IVisitable
{{
void
void Accept(IVisitor
Accept(IVisitor v);
v);
}}
class
class Token:
Token: IToken,
IToken, IVisitable
IVisitable
{{ ... Token
Token
...
}} «« concrete
concrete »»
 A class can implement one or more interfaces
 An interface can extend zero or more interfaces
 A class can be more accessible than its base interfaces
 An interface cannot be more accessible than its base
interfaces
 A class must implement all inherited interface methods
63
Interface Methods
 The implementing method must be the same as the
interface method
 The implementing method can be virtual or non-
virtual
class
class Token:
Token: IToken,
IToken, IVisitable
IVisitable
{{
Same
Sameaccess
access
public
public virtual
virtual string
string Name(
Name( )) Same
Samereturn
returntype
type
{{ ...
... Same name
Same name
}} Same
Sameparameters
parameters
public
public void
void Accept(IVisitor
Accept(IVisitor v)v)
{{ ...
...
}}
}}
64
Interface Methods Explicitly
• Use the fully qualified interface method name
• Restrictions of explicit interface method implementation
– You can only access methods through the interface
– You cannot declare methods as virtual
– You cannot specify an access modifier

class
class Token:
Token: IToken,
IToken, IVisitable
IVisitable
{{
string
string IToken.Name(
IToken.Name( ))
{{ ...
...
}}
void
void IVisitable.Accept(IVisitor
IVisitable.Accept(IVisitor v)
v)
{{ ...
...
}}
}}
65
Interface : Example -1
interface Interface1 public static void Main()
{ int Add(int x, int y); } { Test1 obj = new Test1();

interface Interface2 obj.Display(obj.Add(3, 7));


{ int Mul(int x, int y); } obj.Display(obj.Mul(3, 7));
Console.Read();
class Test1 : Interface1, Interface2 }
{ public int Add(int x, int y) }
{ return x + y; }
public int Mul(int x, int y) Output:
{ return x * y; } Result 10
public void Display(int r) Result 21
{ Console .WriteLine ("Result "+ r);
}

66
Interface : Example -2
interface Display class InterfaceTest2
{ void Print(); } {
class B1 : Display public static void Main()
{ public void Print() {
{ Console.WriteLine("Base Display"); } D1 dobj = new D1();
} dobj.Print();
class D1 : B1 E1 eobj = new E1();
{ public new void Print() eobj.Print();
{ Console.WriteLine("Derived Display dis = (Display)eobj ;
Display"); } dis.Print();
} }}
class E1 : D1
Output:
{ Derived Display
public new void Print() Derived class E1 – Display
{ Console.WriteLine("Derived class E1- Base Display
Display"); }
67
}
Interface : Example -3
interface I1 public static void Main()
{ {
int Calculate(int x); Explicit_InterfaceTest3 obj = new
} Explicit_InterfaceTest3();
interface I2 I1 ivar1 = (I1)obj;
{ Console.WriteLine ("Interface 1-
int Calculate(int x); Calculate =
} "+ivar1.Calculate(3));
class Explicit_InterfaceTest3 : I1,I2 I2 ivar2 = (I2)obj;
{ Console.WriteLine ("Interface 2-
int I1.Calculate(int x) Calculate =
{ "+ivar2.Calculate(4));
return x*x+x; Console.Read();
} }
int I2.Calculate(int x) }Output:
{ Interface 1 – Calculate = 12
return 2* x ; Interface 2 – Calculate = 8 68
}
Abstract Classes

69
Abstract Classes

 Declaring Abstract Classes


 Abstract Classes in a Class Hierarchy
 Abstract Classes & Interfaces
 Abstract Methods

70
Abstract Classes
 An abstract class is one that cannot be instantiated
 Intended to be used as a base class
 May contain abstract and non-abstract
function members
 Similar to an interface
 Cannot be sealed

71
Abstract Classes
 Use the abstract keyword

abstract
abstract class
class Token
Token
{{
...
...
}}
class Token
Token
class Test
Test
{{ {{ abstract
abstract }}
static
static void
void Main(
Main( ))
{{

}}
new
new Token(
Token( );
); An
Anabstract
abstractclass
be
classcannot
instantiated
cannot
be instantiated

}}

72
Abstract Classes in a Class Hierarchy
interface
interface IToken
IToken
{{ IToken
IToken
string
string Name(
Name( );
); «« interface
interface »»
}}
abstract
abstract class
class Token:
Token: IToken
IToken
{{
string
string IToken.Name(
IToken.Name( )) Token
Token
{{ ... {{ abstract
}}
... abstract }}
...
...
}}
class
class CommentToken:
CommentToken: Token
Token Comment
Comment Keyword
Keyword
{{ ...
...
}} Token
Token Token
Token
class
class KeywordToken:
KeywordToken: Token
Token «« concrete
concrete »» «« concrete
concrete »»
{{ ...
...
}}

73
Abstract Classes in a Class Hierarchy (Cont.)
interface
interface IToken
IToken IToken
IToken
{{
string «« interface
interface »»
string Name(
Name( );
);
}}
abstract
abstract class
class Token
Token
{{
public Token
Token
public virtual
virtual string
string Name(
Name( ))
{{ ...
... {{ abstract
abstract }}
}}
...
...
}}
class
class CommentToken:
CommentToken: Token,
Token, IToken
IToken
Comment
Comment Keyword
Keyword
{{ ...
... Token
Token Token
Token
}}
class «« concrete
concrete »» «« concrete
concrete »»
class KeywordToken:
KeywordToken: Token,
Token, IToken
IToken
{{ ...
...
}}

74
Abstract Classes & Interfaces
 Similarities
 Neither can be instantiated
 Neither can be sealed
 Differences
 Interfaces cannot contain any implementation
 Interfaces cannot declare non-public members
 Interfaces cannot extend non-interfaces

75
Abstract Methods
 Syntax: Use the abstract keyword
 Only abstract classes can declare abstract
methods
 Abstract methods cannot contain a method
body

abstract
abstract class
class Token
Token
{{
public
public virtual
virtual string
string Name(
Name( )) {{ ...
... }}
public
public abstract
abstract int
int Length(
Length( );
);
}}
class
class CommentToken:
CommentToken: Token
Token
{{
public
public override
override string
string Name(
Name( )) {{ ...
... }}
public
public override
override int
int Length(
Length( )) {{ ...
... }} 76
}}
Abstract Methods (Cont.)

 Abstract methods are virtual


 Override methods can override abstract
methods in further derived classes
 Abstract methods can override base class
methods declared as virtual
 Abstract methods can override base class
methods declared as override

77
Abstract Class & Abstract Method : Example
public abstract class ABS public override void show()
{ protected int top; { Console.WriteLine("show method in
protected int left; Class2 :{0},{1}\n", top, left); }
public ABS(int top, int left) }
{ this.top = top; class Abstract_Test
this.left = left; } {
public abstract void show(); public static void Main()
} { ABS[] array = new ABS[3];
public class Class1 : ABS array[0] = new Class1(1, 2, "first");
{ private string classvalue; array[1] = new Class1(3, 4, "second");
public Class1(int top, int left, string contents) array[2] = new Class2(5,6);
: base(top, left) for (int i = 0; i < array.Length; i++)
{ classvalue = contents; } array[i].show();
public override void show() } }
{ Console.WriteLine("show method in
Class1 :{0}\n", classvalue); }
Output:
}
show method in Class1 : first
public class Class2 : ABS
show method in Class1 : second
{ public Class2(int top, int left) : base(top, 78
show method in Class2 : 5,6
left) {}
79

You might also like