Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes and Objects: A Deeper Look

Similar presentations


Presentation on theme: "Classes and Objects: A Deeper Look"— Presentation transcript:

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

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

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

4 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

5 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

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

7 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

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

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

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

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

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

13 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

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

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

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

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

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

19 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

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

21 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

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

23 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

24 Outline Time.vb (3 of 5 ) Validation

25 Outline Validation Time.vb (4 of 5 ) Validation

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

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

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

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

30 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

31 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

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

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

34 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

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

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

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

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

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

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

41 Outline Day.vb (4 of 4 )

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

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

44 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

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

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

47 Create new Time object Outline MeTest.vb

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

49 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

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

51 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

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

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

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

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

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

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

58 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

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

60 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

61 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

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

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

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

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

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

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

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

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

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

71 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

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

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

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

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

76 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 and Fig. 9.21)

77 Fig. 9.18 | Creating a Class Library Project.

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

79 Outline Time.vb (2 of 4 )

80 Outline Time.vb (3 of 4 )

81 Outline Time.vb (4 of 4 )

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

83 Fig. 9.21 | Adding a Reference.

84 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

85 Fig. 9.22 | Class diagram with visibility markers.

86 Fig. 9.23 | Class diagram with navigability arrows.

87 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

88 Outline Class for Withdrawal Empty no-argument constructor

89 Outline Declare instance variables

90 Outline Declare references to other objects

91 Outline Declare shell of a Sub method

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

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

94 Outline (2 of 2 )


Download ppt "Classes and Objects: A Deeper Look"

Similar presentations


Ads by Google