SlideShare une entreprise Scribd logo
1  sur  60
Microsoft Visual C# 2010
        Fourth Edition



          Chapter 9
  Using Classes and Objects
Objectives
• Learn about class concepts
• Create classes from which objects can be
  instantiated
• Create objects
• Create properties, including auto-implemented
  properties




Microsoft Visual C# 2010, Fourth Edition          2
Objectives (cont'd.)
• Learn about using public fields and private
  methods
• Learn about the this reference
• Write constructors and use them
• Use object initializers
• Overload operators




Microsoft Visual C# 2010, Fourth Edition        3
Objectives (cont'd.)
• Declare an array of objects and use the Sort() and
  BinarySearch() methods with them
• Write destructors
• Understand GUI application objects




Microsoft Visual C# 2010, Fourth Edition          4
Understanding Class Concepts
• Types of classes
    – Classes that are only application programs with a
      Main() method
    – Classes from which you instantiate objects
          • Can contain a Main() method, but it is not required
• Everything is an object
    – Every object is a member of a more general class
• An object is an instantiation of a class
• Instance variables
    – Data components of a class
Microsoft Visual C# 2010, Fourth Edition                          5
Understanding Class Concepts
                   (cont'd.)
• Fields
    – Object attributes
• State
    – Set of contents of an object’s instance variables
• Instance methods
    – Methods associated with objects
    – Every instance of the class has the same methods
• Class client or class user
    – Program or class that instantiates objects of another
      prewritten class
Microsoft Visual C# 2010, Fourth Edition                      6
Creating a Class from Which Objects
          Can Be Instantiated
• Class header or class definition parts
    – An optional access modifier
    – The keyword class
    – Any legal identifier for the name of your class
• Class access modifiers
    –   public
    –   protected
    –   internal
    –   private


Microsoft Visual C# 2010, Fourth Edition                7
Creating a Class from Which Objects
     Can Be Instantiated (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   8
Creating Instance Variables and
                    Methods
• When creating a class, define both its attributes and
  its methods
• Field access modifiers
    – new, public, protected, internal, private,
      static, readonly, and volatile
• Most class fields are nonstatic and private
    – Provides the highest level of security




Microsoft Visual C# 2010, Fourth Edition              9
Creating Instance Variables and
               Methods (cont'd.)
• Using private fields within classes is an example
  of information hiding
• Most class methods are public
• private data/public method arrangement
    – Allows you to control outside access to your data
• Composition
    – Using an object within another object
    – Defines a has-a relationship



Microsoft Visual C# 2010, Fourth Edition                  10
Creating Instance Variables and
               Methods (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   11
Creating Objects

• Declaring a class does not create any actual objects
• Two-step process to create an object
    – Supply a type and an identifier
    – Create the object, which allocates memory for it
• Reference type
    – Identifiers for objects are references to their memory
      addresses
• When you create an object, you call its constructor



Microsoft Visual C# 2010, Fourth Edition                   12
Creating Objects (cont'd.)



                                                   Invoking constructor




                                           Invoking an object’s method




Microsoft Visual C# 2010, Fourth Edition                                  13
Passing Objects to Methods

• You can pass objects to methods
    – Just as you can simple data types




Microsoft Visual C# 2010, Fourth Edition   14
Passing Objects to Methods (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   15
Creating Properties

• Property
    – A member of a class that provides access to a field of
      a class
    – Defines how fields will be set and retrieved
• Properties have accessors
    – set accessors for setting an object’s fields
    – get accessors for retrieving the stored values
• Read-only property
    – Has only a get accessor


Microsoft Visual C# 2010, Fourth Edition                  16
Creating Properties (cont'd.)




Microsoft Visual C# 2010, Fourth Edition     17
Creating Properties (cont'd.)

• Implicit parameter
    – One that is undeclared and that gets its value
      automatically
• Contextual keywords
    – Identifiers that act like keywords in specific
      circumstances
    – get, set, value, partial, where, and yield




Microsoft Visual C# 2010, Fourth Edition               18
Creating Properties (cont'd.)




Microsoft Visual C# 2010, Fourth Edition     19
Using Auto-Implemented Properties

• Auto-implemented property
    – The property’s implementation is created for you
      automatically with the assumption that:
          • The set accessor should simply assign a value to the
            appropriate field
          • The get accessor should simply return the field
• When you use an auto-implemented property:
    – You do not need to declare the field that corresponds
      to the property



Microsoft Visual C# 2010, Fourth Edition                       20
Using Auto-Implemented Properties
                 (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   21
More About public and private
            Access Modifiers
• Occasionally you need to create public fields or
  private methods
    – You can create a public data field when you want all
      objects of a class to contain the same value
• A named constant within a class is always static
    – Belongs to the entire class, not to any particular
      instance




Microsoft Visual C# 2010, Fourth Edition                   22
More About public and private
         Access Modifiers (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   23
More About public and private
         Access Modifiers (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   24
Understanding the this Reference
• You might eventually create thousands of objects
  from a class
    – Each object does not need to store its own copy of
      each property and method
• this reference
    – Implicitly passed reference
• When you call a method, you automatically pass the
  this reference to the method
    – Tells the method which instance of the class to use



Microsoft Visual C# 2010, Fourth Edition                    25
Understanding the this Reference
                (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   26
Understanding the this Reference
                (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   27
Understanding the this Reference
                (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   28
Understanding Constructors

• Constructor
    – Method that instantiates an object
• Default constructor
    – Automatically supplied constructor without parameters
• Default value of the object
    – The value of an object initialized with a default
      constructor




Microsoft Visual C# 2010, Fourth Edition                  29
Passing Parameters to Constructors

• Parameterless constructor
    – Constructor that takes no arguments
• You can create a constructor that receives
  arguments
• Using the constructor
         Employee partTimeWorker = new Employee(12.50);




Microsoft Visual C# 2010, Fourth Edition              30
Passing Parameters to Constructors
               (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   31
Overloading Constructors
• C# automatically provides a default constructor
    – Until you provide your own constructor
• Constructors can be overloaded
    – You can write as many constructors as you want
          • As long as their argument lists do not cause ambiguity




Microsoft Visual C# 2010, Fourth Edition                         32
Overloading Constructors (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   33
Overloading Constructors (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   34
Using Constructor Initializers
• Constructor initializer
    – Clause that indicates another instance of a class
      constructor should be executed
          • Before any statements in the current constructor body




Microsoft Visual C# 2010, Fourth Edition                        35
Using Constructor Initializers (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   36
Using Object Initializers
• Object initializer
    – Allows you to assign values to any accessible
      members or properties of a class at the time of
      instantiation
          • Without calling a constructor with parameters
• For you to use object initializers, a class must have a
  default constructor




Microsoft Visual C# 2010, Fourth Edition                    37
Using Object Initializers (cont'd.)




Microsoft Visual C# 2010, Fourth Edition      38
Using Object Initializers (cont'd.)
• Using object initializers allows you to:
    – Create multiple objects with different initial
      assignments
          • Without having to provide multiple constructors to cover
            every possible situation
    – Create objects with different starting values for
      different properties of the same data type




Microsoft Visual C# 2010, Fourth Edition                          39
Using Object Initializers (cont'd.)




Microsoft Visual C# 2010, Fourth Edition      40
Using Object Initializers (cont'd.)




Microsoft Visual C# 2010, Fourth Edition      41
Overloading Operators
• Overload operators
    – Enable you to use arithmetic symbols with your own
      objects
• Overloadable unary operators:
        + - ! ~ ++ -- true false
• Overloadable binary operators:
        + - * / % & | ^ == != > < >= <=
• Cannot overload the following operators:
        = && || ?? ?: checked unchecked new
        typeof as is
• Cannot overload an operator for a built-in data type
Microsoft Visual C# 2010, Fourth Edition                   42
Overloading Operators (cont'd.)
• When a binary operator is overloaded and has a
  corresponding assignment operator:
    – It is also overloaded
• Some operators must be overloaded in pairs:
        == with !=, and < with >
• Syntax to overload unary operators:
        type operator overloadable-operator (type identifier)
• Syntax to overload binary operators:
        type operator overloadable-operator (type identifier,
        type operand)

Microsoft Visual C# 2010, Fourth Edition                   43
Overloading Operators (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   44
Overloading Operators (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   45
Declaring an Array of Objects
• You can declare arrays that hold elements of any
  type
    – Including objects
• Example
    Employee[] empArray = new Employee[7];

    for(int x = 0; x < empArray.Length; ++x)
       empArray[x] = new Employee();




Microsoft Visual C# 2010, Fourth Edition             46
Using the Sort() and BinarySearch()
     Methods with Arrays of Objects
• CompareTo() method
    – Provides the details of how the basic data types
      compare to each other
    – Used by the Sort() and BinarySearch() methods
• When you create a class that contains many fields
    – Tell the compiler which field to use when making
      comparisons
          • Use an interface




 Microsoft Visual C# 2010, Fourth Edition                47
Using the Sort() and BinarySearch()
 Methods with Arrays of Objects (cont'd.)
 • Interface
     – Collection of methods that can be used by any class
           • As long as the class provides a definition to override the
             interface’s do-nothing, or abstract, method definitions
 • When a method overrides another:
     – It takes precedence, hiding the original version
 • IComparable interface
     – Contains the definition for the CompareTo() method
           • Compares one object to another and returns an integer


 Microsoft Visual C# 2010, Fourth Edition                           48
Using the Sort() and BinarySearch()
 Methods with Arrays of Objects (cont'd.)




 Microsoft Visual C# 2010, Fourth Edition   49
Using the Sort() and BinarySearch()
 Methods with Arrays of Objects (cont'd.)




 Microsoft Visual C# 2010, Fourth Edition   50
Using the Sort() and BinarySearch()
 Methods with Arrays of Objects (cont'd.)




 Microsoft Visual C# 2010, Fourth Edition   51
Using the Sort() and BinarySearch()
 Methods with Arrays of Objects (cont'd.)




 Microsoft Visual C# 2010, Fourth Edition   52
Understanding Destructors
• Destructor
    – Contains the actions you require when an instance of
      a class is destroyed
• Most often, an instance of a class is destroyed when
  it goes out of scope
• Explicitly declare a destructor
    – Identifier consists of a tilde (~) followed by the class
      name




Microsoft Visual C# 2010, Fourth Edition                         53
Understanding Destructors (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   54
Understanding Destructors (cont'd.)




Microsoft Visual C# 2010, Fourth Edition   55
Understanding GUI Application
                    Objects
• Objects you have been using in GUI applications
  are objects just like others
    – They encapsulate properties and methods




Microsoft Visual C# 2010, Fourth Edition            56
You Do It
• Activities to explore
    –   Creating a Class and Objects
    –   Using Auto-Implemented Properties
    –   Adding Overloaded Constructors to a Class
    –   Creating an Array of Objects




Microsoft Visual C# 2010, Fourth Edition            57
Summary
• You can create classes that are only programs with
  a Main() method and classes from which you
  instantiate objects
• When creating a class:
     – Must assign a name to it and determine what data
       and methods will be part of the class
     – Usually declare instance variables to be private
       and instance methods to be public
• When creating an object:
     – Supply a type and an identifier, and you allocate
       computer memory for that object
Microsoft Visual C# 2010, Fourth Edition                   58
Summary (cont'd.)
• A property is a member of a class that provides
  access to a field of a class
• Class organization within a single file or separate
  files
• Each instantiation of a class accesses the same
  copy of its methods
• A constructor is a method that instantiates (creates
  an instance of) an object
• You can pass one or more arguments to a
  constructor

Microsoft Visual C# 2010, Fourth Edition             59
Summary (cont'd.)
• Constructors can be overloaded
• You can pass objects to methods just as you can
  simple data types
• You can overload operators to use with objects
• You can declare arrays that hold elements of any
  type, including objects
• A destructor contains the actions you require when
  an instance of a class is destroyed



Microsoft Visual C# 2010, Fourth Edition           60

Contenu connexe

Tendances

9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02Terry Yoast
 
Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...Warren0989
 
Generating UML Models with Inferred Types from Pharo Code
Generating UML Models with Inferred Types from Pharo CodeGenerating UML Models with Inferred Types from Pharo Code
Generating UML Models with Inferred Types from Pharo CodeESUG
 
9781439035665 ppt ch04
9781439035665 ppt ch049781439035665 ppt ch04
9781439035665 ppt ch04Terry Yoast
 
9781439035665 ppt ch06
9781439035665 ppt ch069781439035665 ppt ch06
9781439035665 ppt ch06Terry Yoast
 
Functions ppt ch06
Functions ppt ch06Functions ppt ch06
Functions ppt ch06Terry Yoast
 
9781439035665 ppt ch02
9781439035665 ppt ch029781439035665 ppt ch02
9781439035665 ppt ch02Terry Yoast
 
Operators and Expressions in C#
Operators and Expressions in C#Operators and Expressions in C#
Operators and Expressions in C#Prasanna Kumar SM
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12Terry Yoast
 
Computer Programming
Computer ProgrammingComputer Programming
Computer ProgrammingBurhan Fakhar
 
Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...
Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...
Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...Jordi Cabot
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaAdan Hubahib
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02Terry Yoast
 

Tendances (20)

Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Chapter 4 5
Chapter 4 5Chapter 4 5
Chapter 4 5
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...
 
Chap02
Chap02Chap02
Chap02
 
JavaScript functions
JavaScript functionsJavaScript functions
JavaScript functions
 
Generating UML Models with Inferred Types from Pharo Code
Generating UML Models with Inferred Types from Pharo CodeGenerating UML Models with Inferred Types from Pharo Code
Generating UML Models with Inferred Types from Pharo Code
 
9781439035665 ppt ch04
9781439035665 ppt ch049781439035665 ppt ch04
9781439035665 ppt ch04
 
9781439035665 ppt ch06
9781439035665 ppt ch069781439035665 ppt ch06
9781439035665 ppt ch06
 
Functions ppt ch06
Functions ppt ch06Functions ppt ch06
Functions ppt ch06
 
Chapter2
Chapter2Chapter2
Chapter2
 
9781439035665 ppt ch02
9781439035665 ppt ch029781439035665 ppt ch02
9781439035665 ppt ch02
 
Operators and Expressions in C#
Operators and Expressions in C#Operators and Expressions in C#
Operators and Expressions in C#
 
9781285852744 ppt ch12
9781285852744 ppt ch129781285852744 ppt ch12
9781285852744 ppt ch12
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...
Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...
Explicating and Reasoning with Model Uncertainty by Marsha Chechik (ECMFA'14 ...
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02
 
7494605
74946057494605
7494605
 

En vedette (14)

Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Chapter 8
Chapter 8Chapter 8
Chapter 8
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 8 communication
Chapter 8 communicationChapter 8 communication
Chapter 8 communication
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chap 2 MGT 162
Chap 2   MGT 162Chap 2   MGT 162
Chap 2 MGT 162
 
Chap 3 MGT162
Chap 3 MGT162Chap 3 MGT162
Chap 3 MGT162
 
Chap 1 MGT 162
Chap 1   MGT 162Chap 1   MGT 162
Chap 1 MGT 162
 
Programming in c#
Programming in c#Programming in c#
Programming in c#
 
C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick LearningOracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 

Similaire à Csc253 chapter 09

Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan collegeahmed hmed
 
Creational Patterns
Creational PatternsCreational Patterns
Creational PatternsAsma CHERIF
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptxSachin Patidar
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2Julie Iskander
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
10265 developing data access solutions with microsoft visual studio 2010
10265 developing data access solutions with microsoft visual studio 201010265 developing data access solutions with microsoft visual studio 2010
10265 developing data access solutions with microsoft visual studio 2010bestip
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code firstMaxim Shaptala
 
Chapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfChapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfKavitaHegde4
 
Chapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxChapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxKavitaHegde4
 
Vb.net session 03
Vb.net session 03Vb.net session 03
Vb.net session 03Niit Care
 
ASP.NET Session 3
ASP.NET Session 3ASP.NET Session 3
ASP.NET Session 3Sisir Ghosh
 

Similaire à Csc253 chapter 09 (20)

Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
Oops
OopsOops
Oops
 
Creational Patterns
Creational PatternsCreational Patterns
Creational Patterns
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Chap01
Chap01Chap01
Chap01
 
L1
L1L1
L1
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
10265 developing data access solutions with microsoft visual studio 2010
10265 developing data access solutions with microsoft visual studio 201010265 developing data access solutions with microsoft visual studio 2010
10265 developing data access solutions with microsoft visual studio 2010
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code first
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code first
 
Chapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfChapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdf
 
Chapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxChapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptx
 
Vb.net session 03
Vb.net session 03Vb.net session 03
Vb.net session 03
 
ASP.NET Session 3
ASP.NET Session 3ASP.NET Session 3
ASP.NET Session 3
 

Dernier

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Dernier (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Csc253 chapter 09

  • 1. Microsoft Visual C# 2010 Fourth Edition Chapter 9 Using Classes and Objects
  • 2. Objectives • Learn about class concepts • Create classes from which objects can be instantiated • Create objects • Create properties, including auto-implemented properties Microsoft Visual C# 2010, Fourth Edition 2
  • 3. Objectives (cont'd.) • Learn about using public fields and private methods • Learn about the this reference • Write constructors and use them • Use object initializers • Overload operators Microsoft Visual C# 2010, Fourth Edition 3
  • 4. Objectives (cont'd.) • Declare an array of objects and use the Sort() and BinarySearch() methods with them • Write destructors • Understand GUI application objects Microsoft Visual C# 2010, Fourth Edition 4
  • 5. Understanding Class Concepts • Types of classes – Classes that are only application programs with a Main() method – Classes from which you instantiate objects • Can contain a Main() method, but it is not required • Everything is an object – Every object is a member of a more general class • An object is an instantiation of a class • Instance variables – Data components of a class Microsoft Visual C# 2010, Fourth Edition 5
  • 6. Understanding Class Concepts (cont'd.) • Fields – Object attributes • State – Set of contents of an object’s instance variables • Instance methods – Methods associated with objects – Every instance of the class has the same methods • Class client or class user – Program or class that instantiates objects of another prewritten class Microsoft Visual C# 2010, Fourth Edition 6
  • 7. Creating a Class from Which Objects Can Be Instantiated • Class header or class definition parts – An optional access modifier – The keyword class – Any legal identifier for the name of your class • Class access modifiers – public – protected – internal – private Microsoft Visual C# 2010, Fourth Edition 7
  • 8. Creating a Class from Which Objects Can Be Instantiated (cont'd.) Microsoft Visual C# 2010, Fourth Edition 8
  • 9. Creating Instance Variables and Methods • When creating a class, define both its attributes and its methods • Field access modifiers – new, public, protected, internal, private, static, readonly, and volatile • Most class fields are nonstatic and private – Provides the highest level of security Microsoft Visual C# 2010, Fourth Edition 9
  • 10. Creating Instance Variables and Methods (cont'd.) • Using private fields within classes is an example of information hiding • Most class methods are public • private data/public method arrangement – Allows you to control outside access to your data • Composition – Using an object within another object – Defines a has-a relationship Microsoft Visual C# 2010, Fourth Edition 10
  • 11. Creating Instance Variables and Methods (cont'd.) Microsoft Visual C# 2010, Fourth Edition 11
  • 12. Creating Objects • Declaring a class does not create any actual objects • Two-step process to create an object – Supply a type and an identifier – Create the object, which allocates memory for it • Reference type – Identifiers for objects are references to their memory addresses • When you create an object, you call its constructor Microsoft Visual C# 2010, Fourth Edition 12
  • 13. Creating Objects (cont'd.) Invoking constructor Invoking an object’s method Microsoft Visual C# 2010, Fourth Edition 13
  • 14. Passing Objects to Methods • You can pass objects to methods – Just as you can simple data types Microsoft Visual C# 2010, Fourth Edition 14
  • 15. Passing Objects to Methods (cont'd.) Microsoft Visual C# 2010, Fourth Edition 15
  • 16. Creating Properties • Property – A member of a class that provides access to a field of a class – Defines how fields will be set and retrieved • Properties have accessors – set accessors for setting an object’s fields – get accessors for retrieving the stored values • Read-only property – Has only a get accessor Microsoft Visual C# 2010, Fourth Edition 16
  • 17. Creating Properties (cont'd.) Microsoft Visual C# 2010, Fourth Edition 17
  • 18. Creating Properties (cont'd.) • Implicit parameter – One that is undeclared and that gets its value automatically • Contextual keywords – Identifiers that act like keywords in specific circumstances – get, set, value, partial, where, and yield Microsoft Visual C# 2010, Fourth Edition 18
  • 19. Creating Properties (cont'd.) Microsoft Visual C# 2010, Fourth Edition 19
  • 20. Using Auto-Implemented Properties • Auto-implemented property – The property’s implementation is created for you automatically with the assumption that: • The set accessor should simply assign a value to the appropriate field • The get accessor should simply return the field • When you use an auto-implemented property: – You do not need to declare the field that corresponds to the property Microsoft Visual C# 2010, Fourth Edition 20
  • 21. Using Auto-Implemented Properties (cont'd.) Microsoft Visual C# 2010, Fourth Edition 21
  • 22. More About public and private Access Modifiers • Occasionally you need to create public fields or private methods – You can create a public data field when you want all objects of a class to contain the same value • A named constant within a class is always static – Belongs to the entire class, not to any particular instance Microsoft Visual C# 2010, Fourth Edition 22
  • 23. More About public and private Access Modifiers (cont'd.) Microsoft Visual C# 2010, Fourth Edition 23
  • 24. More About public and private Access Modifiers (cont'd.) Microsoft Visual C# 2010, Fourth Edition 24
  • 25. Understanding the this Reference • You might eventually create thousands of objects from a class – Each object does not need to store its own copy of each property and method • this reference – Implicitly passed reference • When you call a method, you automatically pass the this reference to the method – Tells the method which instance of the class to use Microsoft Visual C# 2010, Fourth Edition 25
  • 26. Understanding the this Reference (cont'd.) Microsoft Visual C# 2010, Fourth Edition 26
  • 27. Understanding the this Reference (cont'd.) Microsoft Visual C# 2010, Fourth Edition 27
  • 28. Understanding the this Reference (cont'd.) Microsoft Visual C# 2010, Fourth Edition 28
  • 29. Understanding Constructors • Constructor – Method that instantiates an object • Default constructor – Automatically supplied constructor without parameters • Default value of the object – The value of an object initialized with a default constructor Microsoft Visual C# 2010, Fourth Edition 29
  • 30. Passing Parameters to Constructors • Parameterless constructor – Constructor that takes no arguments • You can create a constructor that receives arguments • Using the constructor Employee partTimeWorker = new Employee(12.50); Microsoft Visual C# 2010, Fourth Edition 30
  • 31. Passing Parameters to Constructors (cont'd.) Microsoft Visual C# 2010, Fourth Edition 31
  • 32. Overloading Constructors • C# automatically provides a default constructor – Until you provide your own constructor • Constructors can be overloaded – You can write as many constructors as you want • As long as their argument lists do not cause ambiguity Microsoft Visual C# 2010, Fourth Edition 32
  • 33. Overloading Constructors (cont'd.) Microsoft Visual C# 2010, Fourth Edition 33
  • 34. Overloading Constructors (cont'd.) Microsoft Visual C# 2010, Fourth Edition 34
  • 35. Using Constructor Initializers • Constructor initializer – Clause that indicates another instance of a class constructor should be executed • Before any statements in the current constructor body Microsoft Visual C# 2010, Fourth Edition 35
  • 36. Using Constructor Initializers (cont'd.) Microsoft Visual C# 2010, Fourth Edition 36
  • 37. Using Object Initializers • Object initializer – Allows you to assign values to any accessible members or properties of a class at the time of instantiation • Without calling a constructor with parameters • For you to use object initializers, a class must have a default constructor Microsoft Visual C# 2010, Fourth Edition 37
  • 38. Using Object Initializers (cont'd.) Microsoft Visual C# 2010, Fourth Edition 38
  • 39. Using Object Initializers (cont'd.) • Using object initializers allows you to: – Create multiple objects with different initial assignments • Without having to provide multiple constructors to cover every possible situation – Create objects with different starting values for different properties of the same data type Microsoft Visual C# 2010, Fourth Edition 39
  • 40. Using Object Initializers (cont'd.) Microsoft Visual C# 2010, Fourth Edition 40
  • 41. Using Object Initializers (cont'd.) Microsoft Visual C# 2010, Fourth Edition 41
  • 42. Overloading Operators • Overload operators – Enable you to use arithmetic symbols with your own objects • Overloadable unary operators: + - ! ~ ++ -- true false • Overloadable binary operators: + - * / % & | ^ == != > < >= <= • Cannot overload the following operators: = && || ?? ?: checked unchecked new typeof as is • Cannot overload an operator for a built-in data type Microsoft Visual C# 2010, Fourth Edition 42
  • 43. Overloading Operators (cont'd.) • When a binary operator is overloaded and has a corresponding assignment operator: – It is also overloaded • Some operators must be overloaded in pairs: == with !=, and < with > • Syntax to overload unary operators: type operator overloadable-operator (type identifier) • Syntax to overload binary operators: type operator overloadable-operator (type identifier, type operand) Microsoft Visual C# 2010, Fourth Edition 43
  • 44. Overloading Operators (cont'd.) Microsoft Visual C# 2010, Fourth Edition 44
  • 45. Overloading Operators (cont'd.) Microsoft Visual C# 2010, Fourth Edition 45
  • 46. Declaring an Array of Objects • You can declare arrays that hold elements of any type – Including objects • Example Employee[] empArray = new Employee[7]; for(int x = 0; x < empArray.Length; ++x) empArray[x] = new Employee(); Microsoft Visual C# 2010, Fourth Edition 46
  • 47. Using the Sort() and BinarySearch() Methods with Arrays of Objects • CompareTo() method – Provides the details of how the basic data types compare to each other – Used by the Sort() and BinarySearch() methods • When you create a class that contains many fields – Tell the compiler which field to use when making comparisons • Use an interface Microsoft Visual C# 2010, Fourth Edition 47
  • 48. Using the Sort() and BinarySearch() Methods with Arrays of Objects (cont'd.) • Interface – Collection of methods that can be used by any class • As long as the class provides a definition to override the interface’s do-nothing, or abstract, method definitions • When a method overrides another: – It takes precedence, hiding the original version • IComparable interface – Contains the definition for the CompareTo() method • Compares one object to another and returns an integer Microsoft Visual C# 2010, Fourth Edition 48
  • 49. Using the Sort() and BinarySearch() Methods with Arrays of Objects (cont'd.) Microsoft Visual C# 2010, Fourth Edition 49
  • 50. Using the Sort() and BinarySearch() Methods with Arrays of Objects (cont'd.) Microsoft Visual C# 2010, Fourth Edition 50
  • 51. Using the Sort() and BinarySearch() Methods with Arrays of Objects (cont'd.) Microsoft Visual C# 2010, Fourth Edition 51
  • 52. Using the Sort() and BinarySearch() Methods with Arrays of Objects (cont'd.) Microsoft Visual C# 2010, Fourth Edition 52
  • 53. Understanding Destructors • Destructor – Contains the actions you require when an instance of a class is destroyed • Most often, an instance of a class is destroyed when it goes out of scope • Explicitly declare a destructor – Identifier consists of a tilde (~) followed by the class name Microsoft Visual C# 2010, Fourth Edition 53
  • 54. Understanding Destructors (cont'd.) Microsoft Visual C# 2010, Fourth Edition 54
  • 55. Understanding Destructors (cont'd.) Microsoft Visual C# 2010, Fourth Edition 55
  • 56. Understanding GUI Application Objects • Objects you have been using in GUI applications are objects just like others – They encapsulate properties and methods Microsoft Visual C# 2010, Fourth Edition 56
  • 57. You Do It • Activities to explore – Creating a Class and Objects – Using Auto-Implemented Properties – Adding Overloaded Constructors to a Class – Creating an Array of Objects Microsoft Visual C# 2010, Fourth Edition 57
  • 58. Summary • You can create classes that are only programs with a Main() method and classes from which you instantiate objects • When creating a class: – Must assign a name to it and determine what data and methods will be part of the class – Usually declare instance variables to be private and instance methods to be public • When creating an object: – Supply a type and an identifier, and you allocate computer memory for that object Microsoft Visual C# 2010, Fourth Edition 58
  • 59. Summary (cont'd.) • A property is a member of a class that provides access to a field of a class • Class organization within a single file or separate files • Each instantiation of a class accesses the same copy of its methods • A constructor is a method that instantiates (creates an instance of) an object • You can pass one or more arguments to a constructor Microsoft Visual C# 2010, Fourth Edition 59
  • 60. Summary (cont'd.) • Constructors can be overloaded • You can pass objects to methods just as you can simple data types • You can overload operators to use with objects • You can declare arrays that hold elements of any type, including objects • A destructor contains the actions you require when an instance of a class is destroyed Microsoft Visual C# 2010, Fourth Edition 60