Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

Similar documents
Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

Chapter 5 Object-Oriented Programming

Object-Oriented Programming in C# (VS 2012)

Java Object Oriented Design. CSC207 Fall 2014

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

Object-Oriented Programming in C# (VS 2015)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Introduction to Programming Microsoft.NET Applications with Visual Studio 2008 (C#)

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

C# Programming: From Problem Analysis to Program Design. Fourth Edition

Data Structures (list, dictionary, tuples, sets, strings)

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Introduction to Programming Using Java (98-388)

Microsoft Visual Basic 2005: Reloaded

CS-202 Introduction to Object Oriented Programming

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

A A B U n i v e r s i t y

Object-Oriented Programming

Inheritance and Polymorphism

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

What are the characteristics of Object Oriented programming language?

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

Inheritance, Polymorphism, and Interfaces

Inheritance. Transitivity

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Object Oriented Design

CS260 Intro to Java & Android 03.Java Language Basics

Informatik II Tutorial 6. Subho Shankar Basu

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Cpt S 122 Data Structures. Introduction to C++ Part II

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

C++ Important Questions with Answers

CS 251 Intermediate Programming Inheritance

Saikat Banerjee Page 1

COP 3330 Final Exam Review

What is Inheritance?

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Computer Science II (20073) Week 1: Review and Inheritance

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Chapter 6 Introduction to Defining Classes

Absolute C++ Walter Savitch

Chapter 4 Defining Classes I


Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Course Syllabus C # Course Title. Who should attend? Course Description

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CLASSES AND OBJECTS IN JAVA

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

ITI Introduction to Computing II

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Introduce C# as Object Oriented programming language. Explain, tokens,

EEE-425 Programming Languages (2013) 1

Chapter 1 Getting Started

C# Language. CSE 409 Advanced Internet Technology

Inheritance, and Polymorphism.

BBM 102 Introduction to Programming II Spring Inheritance

Informatik II (D-ITET) Tutorial 6

Microsoft Visual Basic 2005: Reloaded

Object Oriented Programming in C#

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

ITI Introduction to Computing II

DOT NET Syllabus (6 Months)

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

DOT NET SYLLABUS FOR 6 MONTHS

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Programming Exercise 14: Inheritance and Polymorphism

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

CO Java SE 8: Fundamentals

Programming II (CS300)

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

Oops known as object-oriented programming language system is the main feature of C# which further support the major features of oops including:

Uka Tarsadia University MCA ( 3rd Semester)/M.Sc.(CA) (1st Semester) Course : / Visual Programming Question Bank

Problem Solving with C++

EEE-425 Programming Languages (2013) 1

More Relationships Between Classes

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Chapter 11. Abstract Data Types and Encapsulation Concepts

Java Fundamentals (II)

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Instantiation of Template class

Ch02. True/False Indicate whether the statement is true or false.

Abstract data types &

Abstract Data Types & Object-Oriented Programming

Object-Oriented Programming

Index COPYRIGHTED MATERIAL

Advanced Programming Using Visual Basic 2008

OVERRIDING. 7/11/2015 Budditha Hettige 82

C# Programming for Developers Course Labs Contents

Lecture 2: Java & Javadoc

2559 : Introduction to Visual Basic.NET Programming with Microsoft.NET

Course Hours

CHAPTER 1: INTRODUCING C# 3

Transcription:

11 Features Advanced Object-Oriented Programming C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 1 4th Edition

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 userdefined classes Create abstract classes that include abstract methods C# Programming: From Problem Analysis to Program Design 2

Chapter Objectives (continued) Distinguish the differences between sealed and abstract classes Become aware of partial classes Design and implement interfaces Understand why polymorphic programming is a common goal in.net Explore generics and learn how to create generic classes and generic methods C# Programming: From Problem Analysis to Program Design 3

Chapter Objectives (continued) Investigate static versus dynamic typing and become aware of when dynamic and var types are used Work through a programming example that illustrates the chapter s concepts C# Programming: From Problem Analysis to Program Design 4

Object-Oriented Language Features Abstraction Generalizing, identifying essential features, hiding nonessential complexities Encapsulation Packaging data and behaviors into a single unit, hiding implementation details Inheritance Extending program units to enable reuse of code Polymorphism Providing multiple (different) implementations of same named behaviors C# Programming: From Problem Analysis to Program Design 5

Component-Based Development Figure 11-1 Component-based development C# Programming: From Problem Analysis to Program Design 6

Component-Based Development (continued) Component-based applications associated with multitier applications (different layers) Business layer(s) classes that perform processing Provide functionality for specific system; provide necessary processing Data access layer - classes for accessing data from text files and databases Presentation layer - User interface tier for user interaction Graphical User Interface such as Windows or Web C# Programming: From Problem Analysis to Program Design 7

Component-Based Development (continued) Components facilitates reuse-based approach Define and implement independent components into systems Components are implemented through classes Takes the form of objects or collection of objects Components can then be packaged with different components and used for other applications Classes can be created that extend functionality of original classes C# Programming: From Problem Analysis to Program Design 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 is 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 11-2 Methods inherited from an object C# Programming: From Problem Analysis to Program Design 10

Inheriting from Other.NET FCL Classes Experienced inheritance when you developed Windows-based programs Form you created inherited characteristics from System.Windows.Forms.Form class Already had title bar, close (X), and minimize buttons Add functionality to your programs with minimal programming Extend System.Windows.Forms.Form class to build GUIs (Button, Label, TextBox, ListBox) C# Programming: From Problem Analysis to Program Design 11

Inheriting from Other.NET FCL Classes Derived class Figure 11-3 Derived class Base class Class listed after the colon is base class class that already has some functionality Class to the left, PresentationGUI, is derived class Derived class is the new class, the user-defined class C# Programming: From Problem Analysis to Program Design 12

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 Base class has Data members defined with a private access modifier Constructors defined with public access modifiers Properties offering public access to data fields C# Programming: From Problem Analysis to Program Design 13

Creating Base Classes for Inheritance Might create a generalized class such as person public class Person { private string idnumber; private string lastname; private string firstname; private int age; Data members C# Programming: From Problem Analysis to Program Design 14

Access Modifiers Class members defined with private access are restricted to members of the current class Data members are defined with private access modifier Private access enables class to protect its data and only allow access to the data through its methods or properties Constructors use public access modifier If they are not public, you would not be able to instantiate objects of the class in other classes Constructors are methods Named the same name as class and has no return type C# Programming: From Problem Analysis to Program Design 15

Creating Base Classes for Inheritance // Constructor with zero arguments public Person( ) { } // Constructor with four arguments public Person (string id, string lname, string fname, int anage) { } idnumber = id; lastname = lname; firstname = fname; age = anage; Continued definition for Person class Notice, constructor is a method, has same name as class (Person), has no return type, and is overloaded C# Programming: From Problem Analysis to Program Design 16

Access Modifiers Properties offer public access to data fields Properties look like data fields, but are implemented as methods Properties provide the getters (accessors) and setters (mutators) for the class Make properties read-only by NOT defining the set Properties often named the same name as their associated data member EXCEPT, property uses Pascal case (starts with capital letter) LastName lastname C# Programming: From Problem Analysis to Program Design 17

Properties // Property for last name public string LastName { } get { } set { } Private data member return lastname; lastname = value; Properties defined with public access they provide access to private data No need to declare value. It is used, almost like magic value refers to the value sent through an assignment statement get, set and value are contextual keywords C# Programming: From Problem Analysis to Program Design 18

Overriding Methods Person class example has two additional methods public override string ToString( ) // Defined in Person public virtual int GetSleepAmt( ) // Defined in Person Can replace a method defined at a higher level with a new definition Use keyword override in method heading in derived class to provide a new definition In order to be an method that can be overridden, keywords virtual, abstract, or override must be part of the heading for the parent class C# Programming: From Problem Analysis to Program Design 19

Overriding Methods Should override the object ToString( ) method Figure 11-4 ToString( ) signature Object s ToString( ) method The Person class example overrides ToString( ) public override string ToString( ) // Defined in Person { return firstname + " " + lastname; } C# Programming: From Problem Analysis to Program Design 20

Virtual Methods (continued) ToString( ) uses the virtual modifier in the Object class, implying that any class can override it ToString( ) method can have many different definitions Example of polymorphism Overriding differs from overloading a method Overridden methods have exactly the same signature Overloaded methods each have a different signature C# Programming: From Problem Analysis to Program Design 21

Creating Derived Classes Derived classes inherit from a base class Derived classes also called subclasses or child classes Derived classes do not have access to change data members defined with private access in the parent or base class Derived classes have access to change data members defined with protected access in the parent or base class C# Programming: From Problem Analysis to Program Design 22

Derived Classes public class Student : Person // Student is derived from Person { private string major; private string studentid; Additional data members public Student( ) { } // Default constructor :base( ) // No arguments sent to base constructor. Indicates which base class constructor to use C# Programming: From Problem Analysis to Program Design 23

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 {... Use base constructor with int and two strings arguments Base constructor must have a constructor with matching signature C# Programming: From Problem Analysis to Program Design 24

Calling the Base Constructor (continued) Student astudent = new Student ("123456789", "Maria", "Woo", "CS", "1111"); First three arguments, "123456789", "Maria", and "Woo", are sent to the constructor for Person class Last two arguments ("CS", "1111") are used by the Student class constructor (for example above) Student anotherstudent = new Student( ); Both Person and Student default constructors (with no parameters) are called when Student( ) is invoked C# Programming: From Problem Analysis to Program Design 25

Using Members of the Base Class Derived classes can directly access any members defined with public or protected access modifiers Objects instantiated from sub classes (like Student) can use any public members of subclass or base class anotherstudent.lastname = "Garcia"; C# Programming: From Problem Analysis to Program Design 26

Calling Overridden Methods of Scope the Base Class Methods defined in subclass take precedence when named the same name as member of a parent class Use keyword base before the method name to call an overridden method of the base class return base.getsleepamt( ) // Calls GetSleepAmt( ) in // parent class Review PresentationGUIWithOneProject_NoDLLs_FirstExample C# Programming: From Problem Analysis to Program Design 27

Relationship between the Person and Student Classes Figure 11-5 Inheritance class diagram C# Programming: From Problem Analysis to Program Design 28

Making Stand-Alone Components Can take Person and Student classes (or any userdefined class) and store in library for future use 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 C# Programming: From Problem Analysis to Program Design 29

Dynamic Link Library (DLL) Several options for creating components One option compile source code into.dll file type Once you have DLL, any application that wants to use it just adds a reference to the DLL That referenced file with the.dll extension becomes part of the application s private assembly Can use the command line to create.dll C# Programming: From Problem Analysis to Program Design 30

Using Visual Studio to Create DLL Files Figure 11-6 Creating a DLL component C# Programming: From Problem Analysis to Program Design 31

Build Instead of Run to Create DLL Create the parent class first in order to use IntelliSense (for sub classes) To illustrate creating stand-along components, separate project created for Person and Student Because Visual Studio assigns the namespace name the same name as the project name (Person), you should change the namespace identifier If you don t change it, when you start adding a reference to a created DLL, it can become confusing Changed to PersonNamespace for the example C# Programming: From Problem Analysis to Program Design 32

Build Instead of Run to Create DLL After typing class, do not run it select BUILD, Build Solution Figure 11-7 Attempting to run a class library file Create new project for subclasses (Student) Again, select Class Library template from Start page Change namespace identifier (StudentNamespace) C# Programming: From Problem Analysis to Program Design 33

Build Instead of Run to Create DLL (continued) Add a new using statement to subclass In Student, add using PersonNamespace; To gain access to base class members in subclass, Add Reference in subclass to base class Use Solution Explorer window DLL is stored in Debug directory under the bin folder wherever you create the project C# Programming: From Problem Analysis to Program Design 34

Add Reference to Base Class One of the first things to do is Add a Reference to the Parent DLL Figure 11-8 Adding a reference to a DLL C# Programming: From Problem Analysis to Program Design 35

Add Reference to Base Class (continued) Use Browse button to locate DLL Figure 11-9 Add Reference dialog box C# Programming: From Problem Analysis to Program Design 36

Add Reference to Base Class (continued) Figure 11-10 Locating the Person.dll component C# Programming: From Problem Analysis to Program Design 37

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 11-11 Namespace reference error C# Programming: From Problem Analysis to Program Design 38

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 39

Creating a Client Application to Use the DLL DLL components can be reused with many different applications Once the.dll is in the library, any number of applications can reference it Instantiate objects of the referenced DLL Two steps Required Add a reference to the DLL components Include a using statement with the namespace name C# Programming: From Problem Analysis to Program Design 40

Creating a Client Application to Use the DLL (continued) Figure 11-12 DLLs referenced in the PresentationGUI class C# Programming: From Problem Analysis to Program Design 41

Declaring an Object of the Component Type Declare object of the subclass (Student) not the base class public class PresentationGUI : System.Windows.Forms.Form { private Student astudent; Instantiate the object astudent = new Student("123456789", "Maria", "Woo", "CS", "1111"); Use members of the derived, base, or referenced classes Review PresentationGUIwithDLLs (and/or LibraryFiles) Examples C# Programming: From Problem Analysis to Program Design 42

Creating a Client Application to Use the DLL (continued) Figure 11-13 PresentationGUI output referencing two DLLs C# Programming: From Problem Analysis to Program Design 43

Using ILDASM to View the Assembly (ILDASM): Intermediate Language Disassembler tool 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 C# Programming: From Problem Analysis to Program Design 44

Using ILDASM to View the Assembly (continued) In order to use ILDASM in Visual Student, must be added as an external tool in Visual Studio (TOOLS, External Tools ) DLL files cannot be modified or viewed as source code Can use ILDASM to view DLL assemblies C# Programming: From Problem Analysis to Program Design 45

ILDASM to View the Assembly Data fields.ctors are constructors IL code for the method Properties converted to methods Figure 11-14 Student.dll assembly from ILDASM C# Programming: From Problem Analysis to Program Design 46

Abstract Classes Useful for implementing abstraction Identify and pull out common characteristics that all objects of that type possess Class created solely for the purpose of inheritance Provide a common definition of a base class so that multiple derived classes can share that definition For example, Person Student, Faculty Person defined as base abstract class Student defined as derived subclass C# Programming: From Problem Analysis to Program Design 47

Abstract Classes Add keyword abstract on class heading [access modifier] abstract class ClassIdentifier { } // Base class Started new project used same classes, added abstract to heading of Person base class (PresentationGUIWithAbstractClassAndInterface Example) public abstract class Person C# Programming: From Problem Analysis to Program Design 48

Abstract Classes Abstract classes used to prohibit other classes from instantiating objects of the class Can create subclasses (derived classes) of the abstract class Derived classes inherit characteristics from base abstract class Objects can only be created using classes derived from the abstract class C# Programming: From Problem Analysis to Program Design 49

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 Every class that derives from the abstract class must provide implementation details for all abstract methods Sign a contract that details how to implement its abstract methods C# Programming: From Problem Analysis to Program Design 50

Abstract Methods (continued) No additional special keywords are used when a new class is defined to inherit from the abstract base class [access modifier] abstract returntype MethodIdentifier ([parameter list]) ; // No { } included Declaration for abstract method ends with semicolon; NO method body or curly braces Syntax error if you use the keyword static or virtual when defining an abstract method C# Programming: From Problem Analysis to Program Design 51

Abstract Methods (continued) // Classes that derive from Person // must provide implementation details // (the body for the method) public abstract string GetExerciseHabits( ); In the derived class, all abstract methods headings include the special keyword override public override string GetExerciseHabits() { } return "Exercises daily"; Defined in Person Defined in Student C# Programming: From Problem Analysis to Program Design 52

Sealed Classes Sealed class cannot be a base class Sealed classes are defined to prevent derivation Objects can be instantiated from the class, but subclasses cannot be derived from it public sealed class SealedClassExample Number of.net classes defined with the sealed modifier Pen and Brushes classes C# Programming: From Problem Analysis to Program Design 53

Sealed Methods If you do not want subclasses to be able to provide new implementation details, add the keyword sealed Helpful when a method has been defined as virtual in a base class Don t seal a method unless that method is itself an override of another method in some base class C# Programming: From Problem Analysis to Program Design 54

Partial Classes Break class up into two or more files Each file uses partial class designation 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 At compile time, the files are merged together C# Programming: From Problem Analysis to Program Design 55

Creating Partial Classes All the files must use the partial keyword All of the partial class definitions must be defined in the same assembly (.exe or.dll file) Class name and accessibility modifiers, such as private or public, must also match // class definition split into two or more source files public partial class ClassIdentifier C# Programming: From Problem Analysis to Program Design 56

Interfaces C# supports single inheritance Classes can implement any number of interfaces Only inherit from a single class, abstract or nonabstract Think of an interface as a class that is totally abstract; all methods are abstract Abstract classes can have abstract and regular methods Classes implementing interface agree to define details for all of the interface s methods C# Programming: From Problem Analysis to Program Design 57

General form Interfaces (continued) [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 58

Defining an Interface Can be defined as member of existing namespace or class OR by compiling it to separate DLL Easy approach is to put the interface in a separate project (like was done with Person and Student) Use the Class Library template from Start page Unlike abstract classes, it is not necessary to use the abstract keyword with methods of interfaces Because all methods are abstract Review LibraryFiles Example C# Programming: From Problem Analysis to Program Design 59

Defining an Interface (continued) Figure 11-15 ITraveler interface To store in Class Library, Build the interface DLL using Build option from BUILD menu C# Programming: From Problem Analysis to Program Design 60

Implement the Interface Follow same steps as with the Person and Student DLLs if you want to store in Class Library Create Class Library File from Start page Compile and Build assembly from BUILD menu option, creating a.dll file In the class implementing the interface, Add Reference to the.dll file Type a using statement (for the namespace identifier) in the class implementing the interface C# Programming: From Problem Analysis to Program Design 61

Implement the Interface (continued) Heading for the class implementing the interface identifies base class and one or more interfaces following the colon (:) [Base class comes first] [modifier] class ClassIdentifier : identifier [, identifier] public class Student : Person, Itraveler For testing purposes, PresentationGUI class in the PresentationGUIAbtractClassAndInterface folder modified to include calls to interface methods Review PresentationGUIWithAbstractClassAndInterface Example C# Programming: From Problem Analysis to Program Design 62

Implement the Interface: PresentationGUI Application Populated by Interface methods Figure 11-16 PresentationGUI output using interface methods C# Programming: From Problem Analysis to Program Design 63

Implement the Interface: PresentationGUI Application GetStartLocation( ), GetDestination( ), and DetermineMiles( ) members of ITraveler interface private void btntravel_click(object sender, EventArgs e) { // GetStartLocation( ), GetDestination( ) and DetermineMiles( ) // methods all defined as abstract methods in ITraveler interface txtbxfrom.text = astudent.getstartlocation(); txtbxto.text = astudent.getdestination(); txtbxmiles.text = astudent.determinemiles().tostring(); txtbxfrom.visible = true; //More statements C# Programming: From Problem Analysis to Program Design 64

.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 Designing the classes to implement interfaces provides common functionality among them C# Programming: From Problem Analysis to Program Design 65

.NET Framework Interfaces (continued).net Array class is an abstract class Array 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 Much of functionality is in place because of the contracts the interfaces are enforcing C# Programming: From Problem Analysis to Program Design 66

Polymorphism Polymorphism is implemented through interfaces, inheritance, and the use of abstract classes Ability for classes to provide different implementations details for methods with same name Determines which method to call or invoke at run time based on which object calls the method (Dynamic binding) Example ToString( ) method Through inheritance, polymorphism is made possible by allowing classes to override base class members C# Programming: From Problem Analysis to Program Design 67

Polymorphic Programming in.net Multiple classes can implement the same interface, each providing different implementation details for its abstract methods Black box concept Classes that derive from abstract classes are forced to include implementation details for any abstract method C# Programming: From Problem Analysis to Program Design 68

Polymorphic Programming in.net (continued) Actual details of the body of interface methods are left up to the classes that implement the interface Method name is the same Every class that implements the interface may have a completely different behavior C# Programming: From Problem Analysis to Program Design 69

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 70

Generic Classes Defined by inserting an identifier between left and right brackets on the class definition line Example public class GenericClass <T> { } public T datamember; //To instantiate an object, replace the T with data type GenericClass <string> anidentifer = new GenericClass <string>( ); C# Programming: From Problem Analysis to Program Design 71

Generic Classes (continued) public class Stack<T> { private T[ ] items; private int stackpointer = 0; public Stack(int size) { items = new T[size]; } Generic Stack class C# Programming: From Problem Analysis to Program Design 72

Generic Classes (continued) public T Pop( ) { return items[--stackpointer]; } public void Push(T anitem) { items[stackpointer] = anitem; stackpointer++; } } Review GenericStack Example C# Programming: From Problem Analysis to Program Design 73

Generic Methods Similar to defining a generic class Can define generic methods that are not part of generic classes Insert identifier between left and right brackets on the method definition line to indicate it is a generic method Then place that identifier either in the parameter list or as a return type or in both places C# Programming: From Problem Analysis to Program Design 74

Generic Methods (continued) public void SwapData <T> (ref T first, ref T second) { T temp; temp = first; first = second; second = temp; } //To call the method, specify the type following method name SwapData <string> (ref firstvalue, ref secondvalue); C# Programming: From Problem Analysis to Program Design 75

Dynamic C# was originally characterized as being a strongly typed language Compiler checks to ensure that only compatible values are attempting to be stored Variables can still be defined as objects and then cast as different data types during run time Additional boxing/unboxing is needed C# Programming: From Problem Analysis to Program Design 76

Dynamic Data Type Object defined using the dynamic keyword can store anything No unboxing or casting is necessary prior to their use With dynamic data types, the type checking occurs at run time Once defined as dynamic, the memory location can hold any value Dynamic types can be used for data types, method parameters or method return types C# Programming: From Problem Analysis to Program Design 77

Dynamic Data Type (continued) dynamic intvalue = 1000; dynamic stringvalue = "C#"; dynamic decimalvalue = 23.45m; dynamic adate = System.DateTime.Today; Console.WriteLine("{0} {1} {2} {3}", intvalue, stringvalue, decimalvalue, adate); 1000C# 23.45 6/16/2013 12:00:00 AM Single dynamic memory location can hold values of different data types C# Programming: From Problem Analysis to Program Design 78

var Data Type Variables declared inside a method can be declared using the var keyword Implicitly typed by the compiler - compiler determines the type One primary difference between dynamic and var is that var data items must be initialized when they are declared Can declare a dynamic memory location and later associate values with it C# Programming: From Problem Analysis to Program Design 79

var Data Type (continued) var somevalue = 1000; Implicitly typed by the compiler Compiler determines the type Compiler infers the type of the variable from the expression on the right side of the initialization statement C# Programming: From Problem Analysis to Program Design 80

StudentGov Application Example Figure 11-18 Problem specification for StudentGov example C# Programming: From Problem Analysis to Program Design 81

StudentGov Application Example (continued) Table 11-1 Data fields organized by class C# Programming: From Problem Analysis to Program Design 82

StudentGov Example (continued) Figure 11-19 Prototype for StudentGov example C# Programming: From Problem Analysis to Program Design 83

StudentGov Example (continued) Figure 11-20 Class diagrams for StudentGov example C# Programming: From Problem Analysis to Program Design 84

StudentGov Example (continued) Figure 11-21 References added to StudentGov example C# Programming: From Problem Analysis to Program Design 85

StudentGov Example (continued) Figure 11-21 References added to StudentGov example (continued) C# Programming: From Problem Analysis to Program Design 86

StudentGov Example (continued) Table 11-2 PresentationGUI property values C# Programming: From Problem Analysis to Program Design 87

StudentGov Example (continued) Table 11-2 PresentationGUI property values (continued) C# Programming: From Problem Analysis to Program Design 88

StudentGov Example (continued) Table 11-2 PresentationGUI property values (continued) C# Programming: From Problem Analysis to Program Design 89

StudentGov Example (continued) Table 11-2 PresentationGUI property values (continued) C# Programming: From Problem Analysis to Program Design 90

StudentGov Example (continued) Figure 11-22 Setting the StartUp Project C# Programming: From Problem Analysis to Program Design 91

StudentGov Application Example (continued) Figure 11-23 Part of the PresentationGUI assembly C# Programming: From Problem Analysis to Program Design 92

StudentGov Application Example (continued) Figure 11-24 Output from StudentGov example C# Programming: From Problem Analysis to Program Design 93

Coding Standards Declare members of a class of the same security level together When declaring methods that have too many arguments to fit on the same line, the leading parenthesis and the first argument should be written on the same line Additional arguments are written on the following line and indented C# Programming: From Problem Analysis to Program Design 94

Resources Comparison of Unified Modeling Language Tools http://en.wikipedia.org/wiki/list_of_uml_tools Generic Classes (C# Programming Guide) http://msdn.microsoft.com/en-us/library/sz6zd40f(vs.80).aspx C# Station Tutorial: Interfaces http://www.csharp-station.com/tutorials/lesson13.asp C# Programming: From Problem Analysis to Program Design 95

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 96

Chapter Summary (continued) Use inheritance to extend the functionality of userdefined classes Abstract classes Abstract methods Sealed classes Partial classes C# Programming: From Problem Analysis to Program Design 97

Chapter Summary (continued) Interfaces Why polymorphic programming? Generics Generic classes Generic methods Dynamic data types var data types C# Programming: From Problem Analysis to Program Design 98