Classes and Objects: A Deeper Look

Slides:



Advertisements
Similar presentations
 Pearson Education, Inc. All rights reserved static Class Members static fields – Also known as class variables – Represents class-wide.
Advertisements

Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
ASP.NET Programming with C# and SQL Server First Edition
 2006 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
Review of C++ Programming Part II Sheng-Fang Huang.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Chapter 8 More Object Concepts
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
 2005 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
1 Introduction to Classes and Objects Chapter 3 Introduction to Classes and Objects Chapter 3.
Reformatted slides from the textbook, C++ How to Program, 6/e Pearson Education, Inc. All rights reserved Chapter 3. [Lecture 02] Introduction to.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CLASSES : A DEEPER LOOK Chapter 9 Part I 1. 2 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition.
 2006 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
Dale Roberts Object Oriented Programming using Java - Final and Static Keywords Dale Roberts, Lecturer Computer Science, IUPUI
 2005 Pearson Education, Inc. All rights reserved Classes and Objects: A Deeper Look.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Chapter 3 (B) 3.5 – 3.7.  Variables declared in a function definition’s body are known as local variables and can be used only from the line of their.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Object-Based Programming in VB.NET. Must Understand Following: Encapsulation Information hiding Abstract Data Type Class, Instance, Reference Variable.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Object-Oriented Programming: Classes and Objects.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
 2007 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Classes and Objects: A Deeper Look
Classes (Part 1) Lecture 3
Polymorphism, Interfaces & Operator Overloading
Introduction to Classes and Objects
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Classes and Objects
Object Oriented Programming using Java - Class Instance Variables
Object-Oriented Programming: Classes and Objects
Object Based Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 9 Object-Oriented Programming: Inheritance
Chapter 6 Methods: A Deeper Look
Chapter 9 Classes: A Deeper Look, Part 1
Lecture 22 Inheritance Richard Gesick.
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look – Exercises UTPA – Fall 2012 This set of slides is revised from.
Object-Oriented Programming: Inheritance
Introduction to Classes and Objects
Object Oriented Programming in java
Classes: A Deeper Look, Part 1
The University of Texas – Pan American
Object-Oriented Programming: Classes and Objects
Object-Oriented Programming: Inheritance and Polymorphism
Object Oriented Programming in java
Classes & Objects A deeper Look Chapter 10 & 11
Classes: A Deeper Look, Part 1
Chapter 9 Introduction To Classes
Introduction to Classes and Objects
Chapter 8 Classes and Objects: A Deeper Look
Classes and Objects Systems Programming.
C++ Object Oriented 1.
Introduction to Classes and Objects
Presentation transcript:

Classes and Objects: A Deeper Look 9 Classes and Objects: A Deeper Look

My object all sublime I shall achieve in time. W. S. Gilbert Is it a world to hide virtues in? William Shakespeare, Twelfth Night This above all: to thine own self be true. William Shakespeare, Hamlet Don’t be “consistent,” but be simply true. Oliver Wendell Holmes, Jr.

OBJECTIVES In this chapter you will learn: What class scope is and how it affects access to class members. To create overloaded constructors that can initialize objects of a class in a variety of ways. To use partial classes to enable one class to span multiple source-code files. How composition enables you to construct classes that are “made out of” other classes. To use Me to refer to the current object’s members. How garbage collection eliminates most “memory leaks.” How Shared class variables help conserve memory. How to create constant members with Const (at compile time) and ReadOnly (at runtime). To use the Object Browser to discover the capabilities of the classes in the Framework Class Library (FCL).

9.1   Introduction 9.2   Time Class Case Study 9.3   Class Scope 9.4   Default and Parameterless Constructors 9.5   Time Class Case Study: Overloaded Constructors 9.6   Partial Classes 9.7   Composition 9.8   Using the Me Reference to Access the Current Object

9.9   Garbage Collection 9.10  Shared Class Members 9.11  Const and ReadOnly Members 9.12  Object Browser 9.13 Time Class Case Study: Creating Class Libraries 9.14 (Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System 9.15 Wrap-Up

9.1 Introduction Object-Oriented Programming concepts and terminology Deeper look at building classes Constructors Partial classes Me reference Shared, Const, and ReadOnly variables

9.2 Time Class Case Study Every class inherits from Object Private methods are called helper methods They can be called only by other methods of the class to support the operation of those methods Constructors are implemented as Sub and not Function Instance variables Can be initialized when they are declared or in a constructor Should maintain consistent (valid) values Public instance variables in a class is a dangerous programming practice Other parts of the program can set these members to invalid values

Outline Explicitly inherit from Object (1 of 4 ) Time.vb (1 of 4 ) Private instance variables Time’s parameter-less constructor Declare method SetTime

Outline Time.vb (2 of 4 ) Validate parameter value before setting instance variable

Outline Time.vb (3 of 4 ) Validate parameter value before setting instance variable Validate parameter value before setting instance variable

Outline Format string (4 of 4 ) Override Object’s ToString method Time.vb (4 of 4 ) Override Object’s ToString method Validation Format string

Common Programming Error 9.1 Using a reference (which, as you know, is initialized to the default value Nothing) before it refers to an actual object results in a NullReferenceException at execution time and causes the program to terminate prematurely. We discuss how to handle exceptions to make programs more robust in Chapter 12, Exception Handling.

9.2 Time Class Case Study (Cont.) Namespace If you do not specify a namespace for a class or module, it is place in the default namespace When a class or module uses another class in the same namespace, an Imports statement is not required Any method of a class can access all the instance variables of the class and can call every method of the class By hiding the implementation, we eliminate the possibility that clients of the class will beocme dependent on the class’s implemtnation details

Outline Create Time object (1 of 3 ) Call time’s properties FrmTimeTest.vb (1 of 3 ) Call time’s properties

Outline FrmTimeTest.vb (2 of 3 ) Call time’s properties

Outline Call time’s properties (3 of 3 ) FrmTimeTest.vb (3 of 3 ) Call time’s methods ToString and ToUniversalString

Software Engineering Observation 9.1 Using an object-oriented programming approach often simplifies method calls by reducing, or even eliminating, the arguments that must be passed. This benefit of object-oriented programming derives from the encapsulation of instance variables within an object.

9.3 Class Scope Class Scope Class’s instance variables and methods belong to its scope Class members are accessible to all of the class’s methods and properties Can be referenced simply by name Outside class’s scope, class members cannot be referenced directly by name For Public members: objectName.memberName For Shared members: ClassName.memberName A shadowed instance variable can be accessed in a method of that class by preceding its name with keyword Me.

9.4 Default and Parameterless Constuctors Default Constructors Provided by the compilier, if a class does not define a constructor Contains no code Takes no parameter Programmers are also able provide a parameterless constructor If there is any constructor(s) for a class, the compiler will not provide a default constructor for that class

Common Programming Error 9.2 If Public constructors are provided for a class, but none of them is a parameterless constructor, and an attempt is made to call a constructor with no arguments to initialize an object of the class, a compilation error occurs. A constructor can be called with no arguments only if there are no constructors for the class (in which case the default constructor is called) or if the class includes a parameterless constructor provided by the programmer.

9.5 Time Class Case Study: Overloaded Constructors Provide multiple constructor definitions with different signatures Different number, type and/or order of parameters The compiler invokes the appropriate overloaded constructor by matching the signature A copy constructor initializes an object by copying value from another object of that type

Outline (1 of 5 ) No-argument constructor One-argument constructor Time.vb (1 of 5 ) No-argument constructor One-argument constructor

Outline Two-argument constructor (2 of 5 ) Three-argument constructor Time.vb (2 of 5 ) Three-argument constructor A copy constructor Providing SetTime with parameters is optional

Outline Time.vb (3 of 5 ) Validation

Outline Validation Time.vb (4 of 5 ) Validation

Outline Override Object’s string representation Time.vb (5 of 5 )

Software Engineering Observation 9.2 When one object of a class has a reference to another object of the same class, the first object can access all of the second object’s data, methods and properties (including those that are Private).

Software Engineering Observation 9.3 Visual Basic classes are reference types, so all Visual Basic objects are passed to methods by reference.

Common Programming Error 9.3 A constructor can call other class methods that use instance variables not yet initialized. Using instance variables before they have been initialized can lead to logic errors.

Outline (1 of 3 ) Invoke Time’s overloaded constructor TimeTest.vb (1 of 3 ) Invoke Time’s overloaded constructor Print time1’s time Print time2’s time

Outline Print time3’s time (2 of 3 ) Print time4’s time TimeTest.vb (2 of 3 ) Print time4’s time Print time5’s time

Outline Print time6’s time TimeTest.vb (3 of 3 )

Software Engineering Observation 9.4 If a method of a class provides functionality required by a constructor (or other method) of the class, call that method from the constructor (or other method). This simplifies the maintenance of the code and reduces the likelihood of code errors.

9.6 Partial Classes Partial classes Visual Basic allows a class declaration to span multiple source-code files Partial modifier Any class declaration with the same class name in the program will be combined with the partial class declaration to form a single class declaration at compile time Must be declared in the same namespace and assembly If members in one source file conflict with those in another source file, a compilation errors will occur

Error-Prevention Tip 9.1 When combining all partial classes, at least one class declaration must have a Partial modifier. Otherwise, a compilation error occurs.

9.7 Composition Composition A class can have references to objects of other classes as members Sometimes referred to as a has-a relationship

Software Engineering Observation 9.5 One form of software reuse is composition, in which a class has as members references to objects of other classes.

Outline Instance variables to represent a day (1 of 4 ) Day.vb (1 of 4 ) A three-parameter constructor

Outline Validates month value Day.vb (2 of 4 )

Outline Call CheckDay to validate day value (3 of 4 ) Day.vb (3 of 4 ) Validates day value

Outline Day.vb (4 of 4 )

Outline Employee contains references to two Day objects Employee.vb Create two new Day objects for birthDate and hireDate

Outline Create an Employee object Display the Employee object CompositionTest. vb Display the Employee object

9.8 Using the Me Reference to Access the Current Object Any object can access a reference to itself with keyword Me Non-Shared methods implicitly use Me when referring to the object’s instance variables and other methods Can be used to access instance variables when they are shadowed by local variables or method parameters

Error-Prevention Tip 9.2 For a method in which a parameter has the same name as an instance variable, use reference Me to access the instance variable explicitly; otherwise, the method parameter is referenced.

Outline Declare instance variables Time.vb Using Me to access the object’s instance variables Using Me explicitly and implicitly to call ToUniversalString

Create new Time object Outline MeTest.vb

Error-Prevention Tip 9.3 Avoid parameter names that conflict with instance variable names to prevent subtle, hard-to-find bugs.

9.9 Garbage Collection Garbage Collection When there are no more references to an object, the object is marked for garbage collection by CLR Automatic memory management that reclaim the memory occupied by objects no longer in use Garbage collector calls a special method named Finalize on each object before it is removed from memory All classes inherits this method No parameter and does not return value Not guaranteed to perform its task at specified time For this reason, programmers should avoid method Finalize Programmers should implement classes from IDisposable

Software Engineering Observation 9.6 A class that uses unmanaged resources, such as files on disk, should provide a method that clients of the class can call explicitly to release the resources. Many Visual Basic library classes provide Close or Dispose methods for this purpose.

9.10 Shared Class Members Shared variables Represents class-wide information Used when: All objects of the class should share the same copy of this instance variable The instance variable should be accessible even when no objects of the class exist Can be accessed with the class name or an object name and a dot (.) Initialization Could be initialized in their declarations Could use a Shared constructor Else, the compiler will initialize it with a default value

Performance Tip 9.1 When a single copy of the data will suffice, use Shared class variables rather than instance variables to save storage and simplify program logic.

Common Programming Error 9.4 Using the Me reference in a Shared method or Shared property is a compilation error.

Common Programming Error 9.5 Explicitly declaring a Shared constructor Public is a compilation error, because a Shared constructor is Public implicitly.

Outline Declare a Shared field (1 of 2 ) Increment Shared field Employee.vb (1 of 2 ) Increment Shared field Decrement Shared field

Outline Employee.vb (2 of 2 ) Declare Shared property Count to get Shared field countValue

Common Programming Error 9.6 A compilation error occurs if a Shared method calls an instance (non-Shared) method in the same class by using only the name of the method. Similarly, a compilation error occurs if a Shared method attempts to access an instance variable in the same class by using only the name of the variable.

9.10 Shared Class Members Garbage Collection Shared method Collect of class GC Indicates that the garbage collector should make a best-effort attempt to reclaim objects eligible for garbage collection It is possible that no objects or only a subset of eligible objects will be collected Shared methods cannot access non-Shared class members Also cannot use the Me reference

Outline Create new Employee objects (1 of 2 ) SharedTest.vb (1 of 2 ) Call Shared property Count using class name Employee

Remove references to objects, CLR will mark them for garbage collection Outline SharedTest.vb (2 of 2 ) Call Shared method Collect of class GC to indicate that garbage collection should be attempted

9.11 Const and ReadOnly Instance Variables Cannot be modified after initialization Must be initialized in its declaration Must be initialized at compile time ReadOnly Can be initialized when declared or inside constructor Is not initialized until runtime If not initialized, then default values are assigned Property ReadOnly keyword Must be included in property header if there is only a Get accessor Must be included in property header if there is only a Set accessor

Error-Prevention Tip 9.4 If a variable’s value should never change, making it a constant prevents it from changing. This helps eliminate errors that might occur if the value of the variable were to change.

Common Programming Error 9.7 Declaring an instance variable as Const but failing to initialize it in that declaration is a compilation error.

Common Programming Error 9.8 Assigning a value to a Const instance variable is a compilation error.

Common Programming Error 9.9 Declaring an instance variable as ReadOnly and attempting to use it before it is initialized is a logic error.

Common Programming Error 9.10 A Shared ReadOnly variable cannot be initialized in an instance constructor for that class, and a ReadOnly instance variable cannot be initialized in a Shared constructor for that class. Attempting to define a ReadOnly variable in an inappropriate constructor is a compilation error.

Common Programming Error 9.11 Declaring a Const member as Shared is a compilation error, because a Const member is Shared implicitly.

Common Programming Error 9.12 Declaring a ReadOnly member as Const is a compilation error, because these two keywords are not allowed to be combined in a variable declaration.

Outline Declare Const and ReadOnly instance variable CircleConstants .vb Const variable cannot be modified ReadOnly variable cannot be modified after constructor call

Outline Create Random object Create CircleConstants object ConstAndReadOnly .vb Create CircleConstants object Output results

9.12 Object Browser Object Browser (Fig. 9.22) Visual Studio’s feature to facilitate object-oriented applications Lists all classes in the Visual Basic library (left frame) Learn the functionality provided by specific classes Methods provided on the upper-right frame Description of members appears in the lower-right frame

Fig. 9.14 | Invoking the Object Browser by right clicking class Random and selecting Go To Definition.

Fig. 9.15 | Invoking the Object Browser by right clicking method Next and selecting Go To Definition.

Fig. 9.16 | Object Browser when user selects class Random from the code editor.

Fig. 9.17 | Object Browser when user selects class Random’s Next method from the code editor.

9.13 Time Class Case Study: Creating Class Library Steps for Declaring and Using a Reusable Class Create a Class Library project (Fig. 9.18) Add the reusable class(es) to the project (Fig. 9.19) Ensure that each reusable class is declared Public (Fig. 9.19) Compile the project to create the assembly that contains the reusable classes In an application that requires the class library, add a reference to the class library. Then specify an Imports statement for the class library and use its class(es) in your application (Fig. 9.20 and Fig. 9.21)

Fig. 9.18 | Creating a Class Library Project.

Outline Time is a Public class so it can be imported Time.vb (1 of 4 )

Outline Time.vb (2 of 4 )

Outline Time.vb (3 of 4 )

Outline Time.vb (4 of 4 )

Outline Imports the TimeLibrary in order to use the Time class TimeLibraryTest. vb

Fig. 9.21 | Adding a Reference.

9.17 (Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System Visibility Attributes normally should be private, methods invoked by clients should be public Visibility markers in UML A plus sign (+) indicates public visibility A minus sign (-) indicates private visibility Navigability Navigability arrows indicate in which direction an association can be traversed Bidirectional navigability Associations with navigability arrows at both ends or no navigability arrows at all can be traversed in either direction

Fig. 9.22 | Class diagram with visibility markers.

Fig. 9.23 | Class diagram with navigability arrows.

9.17 (Optional) Software Engineering Case Study: Starting to Program the Classes of the ATM System (Cont.) Implementing the ATM system from its UML design (for each class) Declare a Public class with the name in the first compartment and an empty no-argument constructor Declare instance variables based on attributes in the second compartment Declare references to other objects based on associations described in the class diagram Declare the shells of the methods based on the operations in the third compartment Use Sub if no return type has been specified

Outline Class for Withdrawal Empty no-argument constructor

Outline Declare instance variables

Outline Declare references to other objects

Outline Declare shell of a Sub method

Software Engineering Observation 9.7 Many UML modeling tools can convert UML-based designs into Visual Basic code, considerably speeding the implementation process. For more information on these “automatic” code generators, refer to the Web resources listed at the end of Section 3.10.

Outline (1 of 2 ) Declare properties for the instance variables

Outline (2 of 2 )