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

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

CIS Intro to Programming in C#

Advanced Programming Using Visual Basic 2008

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Building Multitier Programs with Classes

9/21/2010. Based on Chapter 2 in Advanced Programming Using Visual Basic.NET by Bradley and Millspaugh

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

Object-Oriented Programming

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

Microsoft Visual Basic 2005: Reloaded

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

1. A Web Form created in Visual Basic can only be displayed in Internet Explorer. True False

Chapter 5 Object-Oriented Programming

Programming II (CS300)

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CS260 Intro to Java & Android 03.Java Language Basics

PROGRAMMING LANGUAGE 2

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

CMSC 132: Object-Oriented Programming II

Chapter 6. Multiform Projects The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Programming II (CS300)

Lecture 18 Tao Wang 1

CS313D: ADVANCED PROGRAMMING LANGUAGE

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

CS11 Introduction to C++ Fall Lecture 7

CMSC 132: Object-Oriented Programming II

Chapter 10 Introduction to Classes

Java Object Oriented Design. CSC207 Fall 2014

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

What are the characteristics of Object Oriented programming language?

Introduction to Programming Using Java (98-388)

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

Computer Science 4U Unit 1. Programming Concepts and Skills Modular Design

Chapter 6 Introduction to Defining Classes

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

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

OVERRIDING. 7/11/2015 Budditha Hettige 82

Inheritance, and Polymorphism.

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

EEE-425 Programming Languages (2013) 1

VB.NET. Exercise 1: Creating Your First Application in Visual Basic.NET

Data Abstraction. Hwansoo Han

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)


What is Inheritance?

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

Microsoft Visual Basic 2005: Reloaded

Programming Using C# QUEEN S UNIVERSITY BELFAST. Practical Week 7

CPS 506 Comparative Programming Languages. Programming Language

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

Introduction to Object- Oriented Programming

Lecture 5: Inheritance

CS313D: ADVANCED PROGRAMMING LANGUAGE

EEE-425 Programming Languages (2013) 1

ECE 3574: Dynamic Polymorphism using Inheritance

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 02 Building Multitier Programs with Classes

Comp 249 Programming Methodology

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Logistics. Final Exam on Friday at 3pm in CHEM 102

M Introduction to Visual Basic.NET Programming with Microsoft.NET 5 Day Course

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

Object Orientated Analysis and Design. Benjamin Kenwright

Data Structures using OOP C++ Lecture 3

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Programming Exercise 14: Inheritance and Polymorphism

Chapter 12 Object-Oriented Programming. Starting Out with Games & Graphics in C++ Tony Gaddis

Sri Vidya College of Engineering & Technology

EMBEDDED SYSTEMS PROGRAMMING OO Basics

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

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

CS304 Object Oriented Programming Final Term

Inheritance and Polymorphism

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

Module 10 Inheritance, Virtual Functions, and Polymorphism

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Object Oriented Design

CS200: Advanced OO in Java

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

Inheritance -- Introduction

Software Design and Analysis for Engineers

Inheritance, Polymorphism, and Interfaces

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Chapter 14 Abstract Classes and Interfaces

Testing Object-Oriented Software. COMP 4004 Fall Notes Adapted from Dr. A. Williams

PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each)

Basics of Object Oriented Programming. Visit for more.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Practice for Chapter 11

Object-Oriented Programming

ECE 122. Engineering Problem Solving with Java

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Chapter 4 Defining Classes I

CS111: PROGRAMMING LANGUAGE II

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Transcription:

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

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

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

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

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

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

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

Object-Oriented Terminology Encapsulation Inheritance Polymorphism Reusable Classes Multitier Applications McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-8

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

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

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

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

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

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

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

Multitier Applications - 2 Common implementation of multitier application McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-16

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Creating a Base Class Strictly for Inheritance - 2 Base Class public abstract class BaseClass { public abstract void somemethod() { // No code allowed here. } } Inherited Class public class DerivedClass : BaseClass { public override void somemethod() { // Code goes here. } } McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-42

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

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 public partial class NewForm : BaseForm 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 McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-44

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

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

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

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

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

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

Using the Object Browser - 2 McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-51

Examining C# Classes - 1 Members of System.Windows.Forms.MessageBox Class McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-52

Examining C# Classes - 2 Display the MessageBoxButtons constants McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-53

Examining Your Own Classes McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. 12-54