Tải bản đầy đủ (.pdf) (7 trang)

x0041 lect8 pol morebook vn 0563

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (182.93 KB, 7 trang )

1

Advanced Programming
Lecture 7
Inheritance


Abstract Classes and Methods
• Abstract classes
– Cannot be instantiated
– Used as base classes
– Class definitions are not complete – derived classes must
define the missing pieces
– Can contain abstract methods and/or abstract properties
• Have no implementation
• Derived classes must override inherited abstract methods and
properties to enable instantiation


Abstract Classes and Methods
• Concrete classes use the keyword override to
provide implementations for all the abstract
methods and properties of the base-class
• Any class with an abstract method or property
must be declared abstract
• Even though abstract classes cannot be
instantiated, we can use abstract class references to
refer to instances of any concrete class derived
from the abstract class



Case Study: Inheriting Interface and 
Implementation
• Abstract base class Shape
– Concrete virtual method Area (default return value is 0)
– Concrete virtual method Volume (default return value is 0)
– Abstract read-only property Name

• Class Point2 inherits from Shape
– Overrides property Name (required)
– Does NOT override methods Area and Volume

• Class Circle2 inherits from Point2
– Overrides property Name
– Overrides method Area, but not Volume

• Class Cylinder2 inherits from Circle2
– Overrides property Name
– Overrides methods Area and Volume


Case Study: Payroll System
• Base-class Employee
– abstract
– abstract method Earnings

• Classes that derive from Employee






Boss
CommissionWorker
PieceWorker
HourlyWorker

• All derived-classes implement method Earnings
• Driver program uses Employee references to refer to
instances of derived-classes
• Polymorphism calls the correct version of Earnings


54

1
// Fig. 10.23: Interfaces2Test.cs
2
// Demonstrating polymorphism with interfaces in
3
// Point-Circle-Cylinder hierarchy.
4
5
using System.Windows.Forms;
6
7
public class Interfaces2Test
8
{
9
public static void Main( string[] args )

10
{
11
// instantiate Point3, Circle3 and Cylinder3
objects
12
Point3 point = new Point3( 7, 11 );
13
Circle3 circle = new Circle3( 22, 8, 3.5 );
14
Cylinder3 cylinder = new Cylinder3( 10, 10,
3.3, 10 );
15
16
// create array of IShape references
17
IShape[] arrayOfShapes = new IShape[ 3 ];
18
19
// arrayOfShapes[ 0 ] references Point3
object
20
arrayOfShapes[ 0 ] = point;
21


55

32
foreach ( IShape shape in arrayOfShapes )

33
{
34
output += "\n\n" + shape.Name + ":\nArea
= " +
35
shape.Area() + "\nVolume = " +
shape.Volume();
36
}
37
38
MessageBox.Show( output, "Demonstrating
Polymorphism" );
39
}
40
}



×