Transcript Chapter 10
10
Advanced Object-Oriented Programming Features
C# Programming: From Problem Analysis to Program Design 2 nd Edition
C# Programming: From Problem Analysis to Program Design 1
Chapter Objectives
• Learn the major features of object-oriented languages • Design and develop multitier applications using component-based development methods • Use
inheritance
to extend the functionality of user-defined classes • Create abstract classes that include abstract methods C# Programming: From Problem Analysis to Program Design 2
Chapter Objectives (
continued
)
• Become aware of partial classes • Design and implement interfaces • Understand why
polymorphic
common goal in .NET
programming is a • Explore generics and learn how to create generic classes and generic methods • Work through a programming example that illustrates the chapter’s concepts C# Programming: From Problem Analysis to Program Design 3
Object-Oriented Language Features-
APIE
•
Abstraction
– Abstract or identify the objects involved in the problem • • • an impractical idea; something visionary and unrealistic.
Polymorphism
– Multiple implementations of the same behaviors
Inheritance
– Reuse of code through extending program units
Encapsulation
– Packaging data and behaviors into a single unit
Tutorial
4
Component-Based Development
Figure 10-1
Component-based development C# Programming: From Problem Analysis to Program Design 5
Component-Based Development (
continued
)
• Multitier applications – Data access tier for accessing data from text files and databases – Graphical user interface tier for user interaction • Windows • Web • Components implemented through classes in C# • Class library files with a dynamic link library (DLL) extension .Class Library 6
Class Library cont…
• In object-oriented programming , a class library is a collection of prewritten class es or coded templates, any of which can be specified and used by a programmer when developing an application program. • The programmer specifies which classes are being used and furnishes data that instantiate s each class as an object that can be called when the program is executed. Access to and use of a class library greatly simplifies the job of the programmer since standard, pretested code is available that the programmer doesn't have to write.
7
Class Library cont…
•
Microsoft Foundation Class Library (MFC Library)
-The Microsoft Foundation Class (MFC) Library is a collection of classes (generalized definitions used in object-oriented programming) that can be used in building application programs.
( WhatIs.com
)
•
Java Foundation Classes (JFC)
Using the Java programming language, Java Foundation Classes (JFC) are pre-written code in the form of class libraries (coded routines) that give the programmer a comprehensive set of graphical use...
( SearchSOA.com
)
•
Template
- A template is a form, mold, or pattern used as a guide to making something.
8
Inheritance
• Enables you to: – Create a general class and then define specialized classes that have access to the members of the general class • Associated with an "is a" relationship – Specialized class “is a” form of the general class • Classes can also have a "has a" relationship, not associated with inheritance – "has a" relationship associated with containment or aggregation C# Programming: From Problem Analysis to Program Design 9
Inheriting from the Object Class
• Every object inherits four methods as long as reference to the System namespace included
Figure 10-2
Methods inherited from an object C# Programming: From Problem Analysis to Program Design 10
Inheriting from Other .NET FCL Classes
• Add functionality to programs with minimal programming with .NET FCL
(Framework class library)
• Extend System.Windows.Forms.Form class to build GUIs (Button, Label, TextBox, ListBox) Derived class Base class
Figure 10-3
Derived class C# Programming: From Problem Analysis to Program Design 11
Creating Base Classes for Inheritance
• Can define your own classes from which other classes can inherit • Base class is called the super or parent class • Data members are defined with a private access modifier • Constructors are defined with public access modifiers • Properties offer public access to data fields – Inheritance from a Base Class in Microsoft.NET
C# Programming: From Problem Analysis to Program Design 12
Overriding Methods
• Replace the method defined at a higher level • Keyword override included in derived class – Base method includes virtual, abstract, or override keyword • Overriding differs from overloading a method – Overridden methods have exactly the same signature – Overloaded methods each have a different signature
Figure 10-4
ToString( ) signature C# Programming: From Problem Analysis to Program Design 13
Overriding Methods (
continued
)
•
Polymorphism
means that many classes can provide the same property or method, and a caller doesn't have to know what class an object belongs to before calling the property or method.
• Example of
polymorphism Overview
– ToString( ) method can have many different definitions – ToString( ) uses the virtual modifier implying any class can override it • Derived classes inherit from a base class – Also called subclasses or child classes • Protected access modifiers – Access only to classes that derived from them – Access to change data in the base class 14
Calling the Base Constructor
• To call the constructor for the base class, add keyword :base between the constructor heading for the subclass and the opening curly brace public Student( string id, string fname, string lname, string maj, int sId) : base (id, lname, fname) // base constructor arguments { . . .
• Base constructor must have a constructor with matching signature C# Programming: From Problem Analysis to Program Design 15
Using Members of the Base Class
• Scope – Methods defined in subclass take precedence when named the same name as member of a parent class • Can call an overridden method of the base class – Use keyword base before the method name return base .GetSleepAmt( ) // Calls GetSleepAmt( ) in // parent class C# Programming: From Problem Analysis to Program Design 16
Relationship Between the Person and Student Classes
Figure 10-5
Inheritance class diagram C# Programming: From Problem Analysis to Program Design 17
Making Stand-alone Components
• Compile class and create an assembly – Assemblies are units configured and deployed in .NET • Classes can be compiled and stored as a dynamic link library (DLL) instead of into the EXE file type • Adds a reference to the DLL – That referenced file with the .dll extension becomes part of the application’s private assembly C# Programming: From Problem Analysis to Program Design 18
Using Visual Studio to Create DLL Files
Figure 10-6
Creating a DLL component C# Programming: From Problem Analysis to Program Design 19
Build Instead of Run to Create DLL
• Create the parent class first in order to use IntelliSense • Create the subclass class in same way as usual, except Build instead of Run the project to create the DLL
Figure 10-7
Attempting to run a class library file C# Programming: From Problem Analysis to Program Design 20
Add Reference to Base Class
One of the first things to do is
Add a Reference
to the Parent DLL
Figure 10-8
Adding a reference to a DLL C# Programming: From Problem Analysis to Program Design 21
Add Reference to Base Class (
continued
)
Use Browse button to locate DLL
Figure 10-9
Add Reference dialog box C# Programming: From Problem Analysis to Program Design 22
Add Reference to Base Class (
continued
)
Figure 10-10
Locating the Person.dll component C# Programming: From Problem Analysis to Program Design 23
Adding a New Using Statement
• In the subclass class, if you simply type the following, you receive an error message public class Student : Person
Figure 10-11
Namespace reference error C# Programming: From Problem Analysis to Program Design 24
Adding a New Using Statement (
continued
)
• To avoid error, could type: public class Student : PersonNamespace.Person
Notice fully qualified name • Better option is to add a using directive using PersonNamespace; // Use whatever name you // typed for the namespace for Person • After typing program statements, build the DLL from the Build option under the Build menu bar C# Programming: From Problem Analysis to Program Design 25
Creating a Client Application To Use the DLL
• DLL components can be reused with many different applications • Two Steps – Add a reference to the DLL components – Include a using statement with the namespace • Then declare an objects of the component type(s) • Use members of the derived, base, or referenced classes C# Programming: From Problem Analysis to Program Design 26
Creating a Client Application To Use the DLL (
continued
)
Figure 10-12
DLLs referenced in the PresentationGUI class C# Programming: From Problem Analysis to Program Design 27
Creating a Client Application To Use the DLL (
continued
)
Figure 10-13
PresentationGUI output referencing two DLLs C# Programming: From Problem Analysis to Program Design 28
(ILDASM):
Intermediate Language Disassembler tool
• The Ildasm.exe
parses
any .NET Framework .exe or .dll assembly, and shows the information in human-readable format. • Ildasm.exe shows more than just the Microsoft intermediate language (MSIL) code — it also displays namespaces and types, including their interfaces. • You can use Ildasm.exe to examine native .NET Framework assemblies, such as Mscorlib.dll, as well as .NET Framework assemblies provided by others or created yourself. Most .NET Framework developers will find Ildasm.exe indispensable.
29
Using ILDASM to View the Assembly
• (ILDASM):
tool Intermediate Language Disassembler
• Assembly shows the signatures of all methods, data fields, and properties • One option – display the source code as a comment in the assembly • Can be run from the command line or from within the Visual Studio IDE – Must be added as an external tool in Visual Studio C# Programming: From Problem Analysis to Program Design 30
Data fields
ILDASM to View the Assembly
.ctors are constructors IL code for the method Properties converted to methods
Figure 10-14
Student.dll assembly from ILDASM C# Programming: From Problem Analysis to Program Design 31
Abstract Classes
• Used to prohibit other classes from instantiating objects of the base class • Still inherit characteristics from base class in subclasses • Base class can have data and method members [access modifier] abstract class ClassIdentifier { } // Base class C# Programming: From Problem Analysis to Program Design 32
Abstract Methods
• Only permitted in abstract classes • Method has no body – Implementation details of the method are left up to classes derived from the base abstract class [access modifier] abstract returnType MethodIdentifier([parameter list]) ; // No { } included • Declaration for abstract method ends with semicolon; NO method body or curly braces C# Programming: From Problem Analysis to Program Design 33
Abstract Methods (
continued
)
• Every class that derives from the abstract class must provide implementation details – Sign a contract that details how to implement its abstract methods – Syntax error if you use the keyword static or virtual when defining an abstract method • No additional special keywords are used when a new class is defined to inherit from the abstract base class C# Programming: From Problem Analysis to Program Design 34
Partial Classes
• Break class up into two or more files – Each file uses partial class designation • New features of C# 2.0
• Used by Visual Studio for Windows applications – Code to initialize controls and set properties is placed in a somewhat hidden file in a region labeled “Windows Form Designer generated code” – File is created following a naming convention of “FormName.Designer.cs” or “xxx.Designer.cs” – Second file stores programmer code C# Programming: From Problem Analysis to Program Design 35
Interfaces
• All .NET languages only support single inheritance • Think of an interface as a class that is totally abstract; all methods are abstract – Abstract classes can have abstract and regular methods – Implementing interface agrees to define details for all of the interface’s methods • Classes can implement any number of interfaces – Only inherit from one class, abstract or nonabstract C# Programming: From Problem Analysis to Program Design 36
Interfaces (
continued
)
• General form [modifier] interface InterfaceIdentifier { // members - no access modifiers are used } • Members can be methods, properties, or events – No implementations details are provided for any of its members C# Programming: From Problem Analysis to Program Design 37
Defining an Interface
• Can be defined as members of a namespace or class or by compiling to a DLL • Easy approach is to put the interface in a separate project – Use the Class Library template • Unlike abstract classes, it is not necessary to use the abstract keyword with methods – Because all methods are abstract C# Programming: From Problem Analysis to Program Design 38
Defining an Interface (
continued
)
Build the interface DLL using
Build
option from
Build
menu bar 39 C# Programming: From Problem Analysis to Program Design
Implement the Interface
• Follow the same steps as with the Person and Student DLLs – Add a reference to the file ending in .dll
– Type a using statement • Heading for the class definition specifies base class and one or more interfaces following the colon (:) [modifier] class ClassIdentifier : identifier [, identifier] • Base class comes first C# Programming: From Problem Analysis to Program Design 40
Implement the Interface: PresentationGUI Application
Figure 10-16
PresentationGUI output using interface methods C# Programming: From Problem Analysis to Program Design 41
.NET Framework Interfaces
• Play an important role in the .NET Framework – Collection classes such as Array class and HashTable class implement a number of interfaces C# Programming: From Problem Analysis to Program Design 42
.NET Framework Interfaces (
continued
)
• .NET Array class is an abstract class – Implements several interfaces (ICloneable; IList; ICollection; and IEnumerable) – Includes methods for manipulating arrays, such as: • Iterating through the elements • Searching by adding elements to the array • Copying, cloning, clearing, and removing elements from the array • Reversing elements • Sorting C# Programming: From Problem Analysis to Program Design 43
NET Framework Interfaces (
continued
)
• HashTable is not abstract – Implements a number of interfaces public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable • Implements the IDeserializationCallback interface • Explore the documentation for these classes and interfaces C# Programming: From Problem Analysis to Program Design 44
Polymorphism
• Ability for classes to provide different implementations of methods called by the same name – ToString( ) method • Dynamic binding – Determines which method to call at run time based on which object calls the method C# Programming: From Problem Analysis to Program Design 45
Polymorphic Programming in .NET
• Multiple classes can implement the same interface, each providing different implementation details for its abstract methods – “Black box” concept • Abstract classes, classes that derive from them, are forced to include implementation details for any abstract method C# Programming: From Problem Analysis to Program Design 46
Generics
• Reduce the need to rewrite algorithms for each data type • Create generic classes, delegates, interfaces, and methods • Identify where data will change in the code segment by putting a placeholder in the code for the type parameters C# Programming: From Problem Analysis to Program Design 47
Generic Classes
• Defined by inserting an identifier between left and right brackets on the class definition line • Example public class GenericClass
string
> anIdentifer = new GenericClass <
string
>( ); C# Programming: From Problem Analysis to Program Design 48
Generic Methods
• Similar to defining a generic class • Insert identifier between left and right brackets on the method definition line to indicate it is a generic method • Example public void SwapData
string
> (
ref
firstValue,
ref
secondValue); C# Programming: From Problem Analysis to Program Design 49
StudentGov Application Example
Figure 10-18
Problem specification for StudentGov example C# Programming: From Problem Analysis to Program Design 50
StudentGov Application Example (
continued
)
C# Programming: From Problem Analysis to Program Design 51
StudentGov Application Example (
continued
)
Figure 10-19
Prototype for StudentGov example C# Programming: From Problem Analysis to Program Design 52
StudentGov Application Example (
continued
)
Figure 10-20
Class diagrams for StudentGov example C# Programming: From Problem Analysis to Program Design 53
StudentGov Application Example (
continued
)
Figure 10-21
References added to StudentGov example C# Programming: From Problem Analysis to Program Design 54
Properties: StudentGov Application
C# Programming: From Problem Analysis to Program Design 55
Properties: StudentGov Application (
continued
)
C# Programming: From Problem Analysis to Program Design 56
StudentGov Application Example (
continued
)
Figure 10-22
Setting the StartUp Project C# Programming: From Problem Analysis to Program Design 57
StudentGov Application Example (
continued
)
Figure 10-23
Part of the PresentationGUI assembly C# Programming: From Problem Analysis to Program Design 58
StudentGov Application Example (
continued
)
Figure 10-24
Output from StudentGov example C# Programming: From Problem Analysis to Program Design 59
Chapter Summary
• Major features of object-oriented languages – Abstraction – Encapsulation – Inheritance – Polymorphism • Multitier applications using component-based development methods C# Programming: From Problem Analysis to Program Design 60
Chapter Summary (
continued
)
• Use inheritance to extend the functionality of user defined classes • Abstract classes – Abstract methods • Partial classes • Interfaces C# Programming: From Problem Analysis to Program Design 61
Chapter Summary (
continued
)
• Why polymorphic programming?
• Generics – Generic Classes – Generic Methods C# Programming: From Problem Analysis to Program Design 62