1 / 96

Advanced Object-Oriented Programming Features in C#

Learn the major features of object-oriented languages, design and develop multitier applications, use inheritance and polymorphism, and explore generics and component-based development.

laine
Download Presentation

Advanced Object-Oriented Programming Features in C#

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. 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

  4. 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

  5. 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

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

  7. 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

  8. 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

  9. 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

  10. Inheriting from the Object Class • Everyobject inherits four methods as long as reference to the System namespace included C# Programming: From Problem Analysis to Program Design

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

  12. Inheriting from Other .NET FCL Classes • 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 Derived class Base class C# Programming: From Problem Analysis to Program Design

  13. 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

  14. 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

  15. 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

  16. Creating Base Classes for Inheritance Continued definition for Person class // Constructor with zero arguments publicPerson( ) { } // Constructor with four arguments public Person (string id, stringlname, stringfname, intanAge) { idNumber= id; lastName= lname; firstName= fname; age = anAge; } 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

  17. 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

  18. Properties // Property for last name public string LastName { get { returnlastName; } set { 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 Private data member C# Programming: From Problem Analysis to Program Design

  19. 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

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

  21. 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

  22. 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 protectedaccess in the parent or base class C# Programming: From Problem Analysis to Program Design

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

  24. 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, stringfname, stringlname, stringmaj, intsId) :base (id, lname, fname) // base constructor arguments { . . . • Base constructor must have a constructor with matching signature Use base constructor with int and two strings arguments C# Programming: From Problem Analysis to Program Design

  25. Calling the Base Constructor (continued) Student aStudent = newStudent ("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

  26. 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

  27. Calling Overridden Methods of the Base Class • Scope • 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 returnbase.GetSleepAmt( ) // Calls GetSleepAmt( ) in // parent class Review PresentationGUIWithOneProject_NoDLLs_FirstExample C# Programming: From Problem Analysis to Program Design

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

  29. Making Stand-Alone Components • Can take Person and Student classes (or any user-defined 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

  30. 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

  31. Using Visual Studio to Create DLL Files C# Programming: From Problem Analysis to Program Design

  32. 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

  33. Build Instead of Run to Create DLL • After typing class, do not run it – select BUILD, Build Solution • 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

  34. Build Instead of Run to Create DLL (continued) • Add a new using statement to subclass • In Student, add usingPersonNamespace; • 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

  35. Add Reference to Base Class One of the first things to do is Add a Reference to the Parent DLL C# Programming: From Problem Analysis to Program Design

  36. Add Reference to Base Class (continued) Use Browse button to locate DLL C# Programming: From Problem Analysis to Program Design

  37. Add Reference to Base Class (continued) C# Programming: From Problem Analysis to Program Design

  38. Adding a New Using Statement • In the subclass class, if you simply type the following, you receive an error message publicclass Student : Person C# Programming: From Problem Analysis to Program Design

  39. Adding a New Using Statement (continued) Notice fully qualified name • To avoid error, could type: publicclass Student : PersonNamespace.Person • Better option is to add a using directive usingPersonNamespace; // 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

  40. 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

  41. Creating a Client Application to Use the DLL (continued) C# Programming: From Problem Analysis to Program Design

  42. Declaring an Object of the Component Type • Declare object of the subclass (Student)…not the base class public class PresentationGUI : System.Windows.Forms.Form { privateStudent 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

  43. Creating a Client Application to Use the DLL (continued) C# Programming: From Problem Analysis to Program Design

  44. 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

  45. Abstract Classes • Add keyword abstract on class heading [access modifier] abstractclassClassIdentifier { } // 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

  46. Abstract Classes C# Programming: From Problem Analysis to Program Design

  47. 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

  48. 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

  49. Abstract Methods (continued) • No additional special keywords are used when a new class is defined to inherit from the abstract base class [access modifier] abstractreturnTypeMethodIdentifier ([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

  50. Abstract Methods (continued) Defined in Person // 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 Student C# Programming: From Problem Analysis to Program Design

More Related