chapter 12 · pdf filechapter 12 oop: creating object-oriented ... •use visual...
TRANSCRIPT
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved.
Chapter 12
OOP: Creating
Object-Oriented
Programs
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-2
Chapter Objectives - 1
• Use object-oriented terminology correctly
• Create a two-tier application that separates the
user interface from the business logic
• Differentiate between a class and an object
• Create a class that has properties and methods
• Declare object variables and assign values to
the properties with a constructor or property
methods
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-3
Chapter Objectives - 2
• Instantiate an object in a project using your class
• Differentiate between static members and instance members
• Understand the purpose of the constructor and destructor methods
• Inherit a new class from your own class
• Use visual inheritance by basing a form on another form
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-4
Object-Oriented Programming
• OOP is currently the most accepted style of programming
• C#, Java, and SmallTalk were designed to be object oriented (OO) from their inception
• Visual Basic and C++ have been modified to accommodate OOP
• As projects become more complex, using objects becomes increasingly important
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-5
Objects - 1
• C# allows the creation of new object types by creating a class – Classes may have properties, methods, and events
• Many built-in choices for objects, such as all tools in the toolbox – The tool represents the class, such as button
– The instance that your create from the class is the object, such as exitButton
• Defining a class creates a definition of what the object looks like and how it behaves – May create as many instances of the class as needed
using the new keyword
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-6
Objects - 2
• Cookie analogy – Cookie cutter is the class
• Cannot eat a cookie cutter
• Can use a cookie cutter to make cookies
– Cookie is the object • Make a cookie using a cookie cutter
– Instantiate the cookie class, creating an object of the class
• Use the same cookie cutter to make various kinds of cookies
• Characteristics of the cookie, flavor or topping, are the properties of the object
Cookie1.Flavor = “Lemon”;
Cookie1.Topping = “Cream Frosting”;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-7
Objects - 3
– Eat, Bake, or Crumble are methods
Cookie1.Crumble();
• Anything the object is told to do is a method
– Tell the cookie to crumble (method)
• If an object does an action and needs to inform the user, that is an event
– The cookie crumbles on its own and informs the user (event)
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-8
Object-Oriented Terminology
• Encapsulation
• Inheritance
• Polymorphism
• Reusable Classes
• Multitier Applications
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-9
Encapsulation
• Refers to the combination of the characteristics
and behaviors of an object
– One “package” or “capsule” that holds the definition of
all properties, methods and events
– Cannot make up new properties or tell the object to
do anything it doesn’t already know how to do
• Can implement data hiding
– An object can expose only those data elements and
methods that it wishes to
• public and private keywords determine access
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-10
Inheritance - 1
• Ability to create a new class from an existing class – Add or modify class variables and methods in a new
class that inherits from an existing class
• An example – Each form created inherits from the existing Form
class
• Original class is called base class, superclass, or parent class
• Inherited class is called subclass, derived class, or child class – Inherited classes have an “is a” relationship with the
base class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-11
Inheritance - 2
• Purpose of inheritance is reusability
– Reuse functionality from one class or object in
another similar situation
– New class created has all characteristics and
actions of the base class
• Additional functionality added to new class
• Common code placed in base class
• Create new classes from base class
– New classes inherit base class methods
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-12
Inheritance - 3
• Person class is an example of reusing
classes
– Base class
• Person
– Subclasses
• Employee
• Customer
• Student
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-13
Polymorphism
• Methods that have identical names but different implementations depending on the specific object or arguments – Radio buttons, check boxes, and list boxes all have a Select
method, which operates appropriately for its class
• Overloading—Several argument lists for calling the method – Example: MessageBox.Show method
• Overriding—A method that has the same signature (name and parameter list) as its base class – Method in subclass takes precedence, or overrides, the
identically named method in the base class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-14
Reusable Classes
• Big advantage of OOP over traditional
programming is ability to reuse classes
• A class can be used in multiple projects
– Each object created from the class has its
own properties
• For any programming situation consider
writing a base class that can be used in
many projects
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-15
Multitier Applications - 1
• Each of the functions in a multitier application
can be coded in a separate component and
stored and run on different machines
• Most popular approach is a three-tier application
– Presentation (user interface), Business (logic) and
Data (retrieve and store in database) tiers
• Goal is to create components that can be
combined and replaced
– If one part of an application needs to change, other
components do not need to be replaced
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-16
Multitier Applications - 2
• Common implementation of multitier application
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-17
Designing Your Own Class - 1
• Analyze the characteristics (variables) and behaviors (methods) needed by a new object
• Example
– A form gathers price and quantity of a product
– Design a class to perform calculation of extended price
• Price, quantity, and extended price are stored in private variables in the class
• Variables are accessed through property methods
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-18
Designing Your Own Class - 2
– The form instantiates the class
– Pass the price and quantity to it through
property procedures
– Call a method to calculate the extended price
– Display the extended price on the form by
retrieving it from a property method
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-19
Designing Your Own Class - 3
• A presentation tier object and a business tier object – The data are entered and displayed in the
presentation tier
– Calculations are performed in the business tier
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-20
Creating Properties in a Class
• Define private member variables inside your
class
– Stores the values for the properties of the class
– Declare all variables as private or protected, not
public, which violates the rules of encapsulation
– Protected variables and methods behave as private
but are available in classes that inherit from the class
• Use property set and get methods to pass
values between a class and the class where
objects of the class are instantiated
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-21
Class Methods
• Create methods of a new class by coding public methods within the class
• Methods declared with the private keyword are available only within the class
• Methods declared with the public keyword are available to external objects created from this class or other classes
• Methods declared with the protected keyword behave as private within the class and any class that inherits from it
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-22
Constructors and Destructors
• A constructor is a method that executes
automatically when an object is
instantiated
– Has the same name as the class
• A destructor is a method that executes
automatically when an object is destroyed
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-23
Constructor
• Executes automatically when an instance (object) of the class is created
• Ideal location for initialization tasks such as setting the initial values of variables and properties
• Constructor must be public because the objects created must execute this method
• If no constructor is written for a class, the compiler creates an implicit default constructor with an empty parameter list
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-24
Overloading the Constructor
• Overloading means that two methods have the
same name but a different list of arguments (the
signature)
• Create overloaded methods in a class
– Give the same name to multiple methods
• Each with a different argument list
– An empty constructor
public ClothingSale()
– A constructor that passes arguments to the class
public ClothingSale(string productNumberString, int quantityInteger,
decimal discountRateDecimal)
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-25
Parameterized Constructor
• A constructor that requires arguments
• Allows arguments to be passed when creating a new object from the class
• Assign incoming values to the properties of the class
– Assign an argument to the property name, which then uses the set method
– Validation is often performed in the set methods
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-26
Creating a New Class –
Step-by-Step
• Add a new class to a project – Choose Project/Add Class
– In the Add New Item dialog box, select Class
– Name the class and click Add
• Define the class properties – Declare private class-level variables to hold the
property values of the new class
– Write the property methods with a public get and a private set method
• Write the constructor
• Code a method
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-27
Property Methods with
Mixed Access Levels
• Set a property statement as public and
then assign a private get or set method
public string EmployeeID { get { return employeeIDString; } private set { employeeIDString = value; } }
Allows public access to
the get method while the
set method is private
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-28
Creating a New Object
Using a Class - 1
• Creating a new class does not create any
objects of the class
– Similar to creating a new tool for the toolbox
• Generally a two-step operation
– Declare the variable
– Instantiate the new object using the new keyword
• Can declare and instantiate in the same
statement ClothingSale aClothingSale = new ClothingSale();
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-29
Creating a New Object
Using a Class - 2
• If an object variable is to be used in multiple methods, declare the object at class level
• Instantiate the object inside of a method at the time the object is needed
– Use a try/catch if converting and passing values entered by a user
• Pass values for the arguments at instantiation when using a parameterized constructor
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-30
Single-Step the Execution
• Quickest and easiest way to debug
• Place a breakpoint on a line of code
• Run the program
• When the program stops at the breakpoint,
press F11 repeatedly and watch each step
• If an error message halts program
execution, point to the variable or property
names to see their current value
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-31
Instance Variables versus
Static Variables
• Instance variables and properties – Separate memory location for each instance of the
object
– Each object created from the class has its own set of properties
– Also called instance members
– An instance member has one copy for each instance or object of the class
• Static variable, property or method – Exists, or is available, for all objects of the class
• Used for a count or total of all objects of the class
– Also called static members
– A static member has one copy for all objects of the class
– Access static members without instantiating an object
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-32
Creating Static Members
• Use the static keyword to create a static member
• Make properties for static members read-only
– Allows values to be retrieved, but not set directly
• A static keyword on a private class-level variable
is required
• The static keyword on a property method is
optional
– Allows a property to be retrieved without creating an
instance of the class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-33
Destructors
• Write a destructor to handle processing needed when an object goes out of scope
• A destructor method has the same name as the class, preceded by a tilde (~)
• Automatically calls the Object.Finalize method from the base class of the object – The programmer has no control over when the
destructor is called • Handled by the CLR as part of garbage collection
• Microsoft advises against writing destructors in classes as it has an adverse effect on the performance of the garbage collector
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-34
Garbage Collection
• Feature of .NET Common Language Runtime (CLR), cleans up unused components
• Periodically checks for unreferenced objects and releases all memory and system resources used by the objects
• Microsoft recommends depending on garbage collection to release resources rather than writing destructors – Don’t know exactly when objects will be finalized
– CLR performs garbage collection on its own schedule
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-35
Inheritance
• A new class can be based on another
class
– Can inherit from
• One of the existing .NET classes
• One of your own classes
– The inheritance clause must follow the class
header prior to any comments
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-36
Inheriting Properties and Methods
• When writing code for a derived class, all
public and protected data members and
methods of the base class can be
referenced
• Use the protected keyword to declare
elements that are accessible only within
their own class or any class derived from
that class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-37
Overriding Methods - 1
• To override a method in C#
– Declare the original method (in the base
class) with the virtual or abstract keyword
– Access modifier for the override method must
be the same as the base-class method
protected virtual decimal calculateExtendedPrice() protected override decimal calculateExtendedPrice()
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-38
Overriding Methods - 2
• Declaring a method in the base class
– Use keywords • virtual
– The method has code that can be overridden
• abstract
– Designed to be overridden by subclasses and have no implementation of their own
– Derived class must provide its own code for the method
– Written strictly for inheritance
– Cannot instantiate an object from an abstract class
• override
– The method is overriding a method in its base class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-39
Accessing Properties - 1
• A derived class can set and retrieve
properties of the base class by using the
property accessor methods
• The subclass constructor uses the base
statement to call the constructor of the
base class
– Argument values can be passed when the
constructor is called
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-40
Accessing Properties - 2
• After assigning values to the properties of
the base class, refer to them in methods of
the derived class
– Properties must have both a get and a set
accessor method
– Read-only or write-only properties cannot be
accessed by name from a derived class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-41
Creating a Base Class
Strictly for Inheritance - 1
• Create a base class solely for the purpose of
inheritance by two or more similar classes
– Include the abstract modifier on the class declaration
– In each method of the base class that must be
overridden, include the abstract modifier
• Method that must be overridden does not contain any code in
the base class
• Must build (compile) the base class before using
it for an inherited class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-42
Creating a Base Class
Strictly for Inheritance - 2
public abstract class BaseClass { public abstract void someMethod() { // No code allowed here. } }
public class DerivedClass : BaseClass { public override void someMethod() { // Code goes here. } }
Base Class
Inherited Class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-43
Inheriting Form Classes - 1
• Projects can require several forms
– May want to use a similar design for all forms
• Use visual inheritance by designing one
form and then inheriting any other forms
• Design the form to be used as the base
class
– Base class inherits from Form and new forms
inherit from the base class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-44
Inheriting Form Classes - 2
• Create the base form and compile the project
• Select Project/Add Windows Form and type the name of the new form
• Choose from two ways to define the inherited form class 1. In code, modify the class header
2. Select the InheritedForm icon (only available in the Professional Edition) Click the Add button, select from the list of compiled forms
in the project that can be used for inheritance
public partial class NewForm : BaseForm
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-45
Inheriting Form Classes - 3
Base Form
Inherited Forms
Inherited controls
(Small arrow in the corner
of controls on inherited forms)
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-46
Coding for Events of
an Inherited Class
• Double-clicking a control on an inherited form does not open the event method
– In the base form’s code declare the control’s event method as public or protected
• Recompile the project
– In the inherited form’s code type the code to write an event for the matching control
• IntelliSense will help with this
• Declare the event as public or protected, must match base class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-47
Setting the Startup Form
• Visual Studio by default begins execution
of C# applications with the Program.cs file
• The first form added to a project is the
startup form
• To change the startup form, modify the
Application.Run method in the Program.cs
file
Application.Run(new MainForm());
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-48
Managing Multiclass Projects
• Form classes must be kept in separate
files
• Other classes do not have to be kept in
separate files
– Code multiple classes in one file
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-49
Adding an Existing Class to a Project
• Two ways to include an existing form or other class in a project
1. Reference the file in its original location
2. Move or copy the file into the project folder (best way)
• Select Project/Add Existing Item to add the file to the project
– Or, right-click the project name in Solution Explorer and select from the context menu
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-50
Using the Object Browser - 1
• Use this helpful tool to view the names,
properties, methods, events, and constants
of C# objects, your own objects, and
objects available from other applications
• To display
– Select View/Object Browser
– Click the Object Browser toolbar button
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-51
Using the Object Browser - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-52
Examining C# Classes - 1
Members of System.Windows.Forms.MessageBox Class
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-53
Examining C# Classes - 2
Display the MessageBoxButtons constants