Kurt Nørmark ©
Department of Computer Science, Aalborg University, Denmark
Abstract Previous lecture Next lecture Index References Contents | In this lecture we will introduce all the fundamental topics in object-oriented programming, which are centered around classes and objects. This includes creation of objects, access to objects, comparison of objects, and object copying. |
Classes: An Initial Example |
The Die Class Slide Annotated slide Contents Index References Textbook | We start with an example: The class Die. This example illustrates many basic ideas behind classes and objects. |
|
Program: The class Die. The class Die encapsulates a couple of variables (numberOfEyes and randomNumberSupplier).
It also implements a number of methods that allow us to use a die. The most important
operation is Toss. |
|
Program: A program that tosses three dice. A program that constructs and tosses a number of dies. |
|
Program: Sample program output. What is printed when we run the program shown above. |
|
Program: The class Die in the namespace Game. |
|
Program: A client of Die from namespace Game. |
|
Program: A slightly more general Die class. This version of class Die is not limited to six sides. It can have an arbitrary
number of sides. |
|
|
Exercise 3.2. Yahtzee | Write a very simple Yahtzee program based on the Die class. Yahtzee is played by use of five dice that are tossed simultaneously. The players are supposed to fill out a table of results. The table should allow registration of ones, ..., sixes, three-of-a-kind, four-of-a-kind, full-house, small-straight, large-straight, yahtzee, and chance. See wikipedia for more details and inspiration. Be sure to use the version of the Die class that shares the Random class with the other dice. This version of the Die class is produced in another exercise in this lecture. This program is for a single player, who tosses the five dice repeatedly. Each time the five dice are tossed a table cell is filled. No re-tossing is done with less than five dice. The first category that fits a given toss is filled. (Try yahtzee first, Chance last). Keep it simple! You may consider to write a YahtzeeTable class which represents the single user table used to register the state of the game. Consider the interface and operations of this class. |
|
Read more about class Die in the text book version of this material. |
Clients and Servers Slide Annotated slide Contents Index References Textbook | A client uses services (operations) of other object. A server provides services (operations) to other objects. The same object can both act as a client and a server. |
|
Interacting Game, Die, and Random objects. The Game object is a client of the Die objects, which in turn are clients of the Random objects. |
|
Read more about clients and servers in the text book version of this material. |
Message Passing Slide Annotated slide Contents Index References Textbook | At the conceptual level, we often talk about message passing in between object. At the underlying, technical level this covers activation of operations - procedure or function calls - on objects. |
|
Interacting Game, Die, and Random objects |
The result sent back is an integral part of the original message - not a new message in its own right. |
Read more about message passing in the text book version of this material. |
Classes |
Classes Slide Annotated slide Contents Index References Textbook | Encapsulation and control of visibility count as the most important ideas of object-oriented programming. |
The concept class: A class encapsulates data and operations that belong together, and it controls the visibility of both data and operations. A class can be used as a type in the programming language |
A class and its interface to other classes. The interface is often called the client interface. In this illustration the operations Op1, Op2, Op3, and Op4 form the client interface of the class. |
The interface - or the client interface - make up those parts of the class that can be used from client classes. The non-interface parts of the class are private to the class. |
Exercise 3.3. Time Classes | This is not a programming exercise, but an exercise which asks you to consider data and operations of classes related to time. Time is very important in our everyday life. Therefore, many of the programs we write somehow deal with time. Design a class PointInTime, which represents a single point in time. How do we represent a point in time? Which variables (data) should be encapsulated in the class? Design the variables in terms of their names and types. Which operations should constitute the client interface of the class? Design the operations in terms of their names, formal parameters (and their types), and the types of their return values. Can you imagine other time-related classes than PointInTime? Avoid looking at the time-related types in the C# library before you solve this exercise. During the course we will come back the time related types in C#. |
Read more about classes in the text book version of this material. |
Visibility - the Iceberg Analogy Slide Annotated slide Contents Index References Textbook | We present two very useful analogies of class visibilities: Icebergs and firewalls. On this slide, the iceberg analogy is in focus. The tip of the iceberg corresponds to the client interface. The part of the iceberg below the surface correspond to the private parts of the class. |
|
An Iceberg. Only a minor fraction of the iceberg is visible above water. In the same way, only a small part of the details of a class should be visible from other classes. |
The details you cannot see, cannot be used directly in other classes. Therefore it is much easier to change the private part of the class than the interface part of the class. This is important because many classes are likely to change a lot during their lifetimes. |
Read more about the iceberg analogy in the text book version of this material. |
Visible and Hidden aspects Slide Annotated slide Contents Index References Textbook | Only the name of the class and the headers (signatures) of some selected operations are visible to client classes. The data (variables) of the class should always be private. |
|
|
Program: The class Die - aspects visible to clients emphasized. On this illustration, the purple aspects correspond to the tip of the iceberg.
Please take a careful look at it and be sure to understand the analogy. |
|
Read more about visibility in the text book version of this material. |
Program modification - the Fire Analogy Slide Annotated slide Contents Index References Textbook | A fire correspond to a modification of a class. We are interested in limiting the consequences of the fire. In the world of OOP, encapsulation and visibility control have the same effect as firewalls in a large building. |
|
Figure. A house - with firewalls - on fire. The fire is not likely to spread to other apartments because of the solid firewalls. |
|
Read more about the firewall analogy in the text book version of this material. |
Representation Independence Slide Annotated slide Contents Index References Textbook | On this page we will illustrate the principle of representation independence. It is done by discussion of a class Point which violates the principle. The class Point has public data representation (rectangular x and y coordinates). We assume that we need to change the rectangular coordinates to so-called polar coordinates (radius and angle). The consequences of this modification of the program is studied via the exercise. |
|
Program: A Point class with public instance variables - NOT Recommended . |
|
Program: A Client of Point. |
|
Program: A version of class Point modified to use polar coordinates - NOT Recommended. |
|
Exercise 3.4. Public data representation | In the accompanying Point and Point client classes the data representation of Point is available to the client class. This may be tempting for the programmer, because we most likely wish to make the x and y coordinates of points available to clients. Why is it a bad solution? It is very important that you can express and explain the problem to fellow programmers. Give it a try! Now assume that we are forced (by the boss) to change the data representation of Point. As a realistic scenario, we may introduce polar coordinates instead of the rectangular x and y coordinates. Recall that polar coordinates consist of a radius and an angle (in radians or degrees). What will happen to client classes, such as this client, when this change is introduced? Is it an easy or a difficult modification to the given client class? Imagine that in a real-life situation we can have thousands of similar lines of code in client programs that refer to x and y coordinates. Rewrite selected parts of class Point such that the client "survives" the change of data representation. In your solution, the instance variables should be private in the Point class. Are you able to make a solution such that the client class should not be changed at all? The private static methods at the bottom of this version of class Point will most likely be helpful. In addition, this version of class Point serves as an initial (but incomplete and somewhat problematic) template of the Point class that you are supposed to write. The client class of Point calculates the distances between pairs of points. This is not a good idea because far too many details occur repeatedly in the client. Suggest a reorganization and implement it. |
|
Read more about representation independence in the text book version of this material. |
Classes in C# Slide Annotated slide Contents Index References Textbook | At this page we take a look at (a simplified version of) the syntactic composition of a class in C#. |
Syntax: The syntactic composition of a C# Class. This is not the whole story. There are other members than variables, constructors and methods. Notice also that it is NOT required that variables come before constructors and that constructors come before methods. |
|
|
|
Read more about classes in C# in the text book version of this material. |
Overview of members in classes Slide Annotated slide Contents Index References | Both variables and methods come in two different flavors: instance related and class related. Class related variables and methods are known as static members in C#. |
|
|
|
On the following four pages we will study instance variables, instance methods, class variables and class methods in relatively great detail. If you do not need this level of detail can can skip these pages, and continue here. |
Instance Variables Slide Annotated slide Contents Index References Textbook | The individual state of objects are contained in instance variables. We illustrate instance variables by the owner, balance and interest rate of bank accounts. The exercise at the bottom of this page explores the visibility of the private instance across two or more instances of class BankAccount. |
The concept instance variable: An instance variable defines a piece of data in the class. Each object, created as an instance of the class, holds a separate copy of the instance variables. |
Program: Instance variables in the class BankAccount. |
|
Program: Creation of three bank accounts. |
|
Program: Output from the BankAccount client program. |
|
Three objects of class BankAccount, each holding three instance variables interestRate, owner, and balance. The values of variables are determined by the bank account transactions that we programmed in the class BankAccountClient. The state of the variables is shown relative to the three WriteLine calls. |
Exercise 3.5. How private are private instance variables? | The purpose of this exercise is to find out how private private instance variables are in C#. Given the BankAccount class. Now modify this class such that each bank account has a backup account. For the backup account you will need a new (private) instance variable of type BankAccount. Modify the Withdraw method, such that if there is not enough money available in the current account, then withdraw the money from the backup account. As an experiment, access the balance of the backup account directly, in the following way: backupAccount.balance -= ... Is it possible to modify the private state of one BankAccount from another BankAccount? Discuss and explain your findings. Are you surprised? |
Read more about instance variables in the text book version of this material. |
Instance Methods Slide Annotated slide Contents Index References Textbook | An instance method is always activated on an object. An instance method can can access instance variables as well as class variables. |
The concept instance method: An instance method is an operation in a class that can read and/or modify one or more instance variables. |
|
|
Program: The BankAccount Class. In this version of class BankAccount we have emphasized five instance methods. |
|
Program: Selected messages to BankAccount methods from a client class. The activation
of the methods represent messages from Main to individual
bank account objects. |
|
Program: Output from the client program. |
|
Program: Methods in the - slightly extended - class BankAccount. A version of class BankAccount with transaction logging. This version of the class
is the basis for the exercise below. |
|
Exercise 3.7. The method LogTransaction in class BankAccount | In the accompanying BankAccount class we have sketched and used a private method named LogTransaction. Implement this private method and test it with the BankAccount client class. |
Exercise 3.7. Course and Project classes | In this exercise you are asked to program three simple classes which keep track of the grading of a sample student. The classes are called BooleanCourse, GradedCourse, and Project. A BooleanCourse encapsulates a course name and a registration of passed/not passed for our sample student. A GradedCourse encapsulates a course name and the grade of the student. For grading we use the Danish 7-step, numerical grades 12, 10, 7, 4, 2, 0 and -3. You are also welcome use the enumeration type ECTSGrade from an earlier exercise. The grade 2 is the lowest passing grade. In both BooleanCourse and GradedCourse you should write a method called Passed. The method is supposed to return whether our sample student passes the course. The class Project aggregates two boolean courses and two graded courses. You can assume that a project is passed if at least three out of the four courses are passed. Write a method Passed in class Project which implements this passing policy. Make a project with four courses, and try out your solution. In this exercise you are supposed to make a simple and rather primitive solution. We will come back to this exercise when we have learned about inheritance and collection classes. |
Read more about instance methods in the text book version of this material. |
Class Variables Slide Annotated slide Contents Index References Textbook | Class variables are less important than instance variables when we do object-oriented programming. Class variables are similar to global variables if they belong to a public class. |
The concept class variable: A class variable belongs to the class, and it is shared among all instances of the class. |
|
Program: The class BankAccount with a class variable. The class BankAccount with a class variable nextAccountNumber, which
can be used as a unique account number when a BankAccount class is instantiated. |
|
Program: A client of class BankAccount. |
|
Program: Output of the BankAccount client program. |
|
Exercise 3.8. Sharing the Random Generator | In the Die class shown in the start of this lecture, each Die object creates its own Random object. We observed that tosses of two or more instances of class Die will be identical. Explain the reason of this behavior. Modify the Die class such that all of them share a single Random object. Consider different ways to implement this sharing. Rerun the Die program and find out if "the parallel tossing pattern" observed above has been alleviated. |
Read more about class variables in the text book version of this material. |
Class Methods Slide Annotated slide Contents Index References Textbook | A class method is activated on a class. In contrast, an instance method is activated on an object. The Main method, which usually initiates our programs, is an example of a class method. |
The concept class method: A class method is associated with the class itself, as opposed to an object of the class |
|
Program: A BankAccount class with static methods. |
|
Program: A client BankAccount. |
|
Program: Output from the BankAccount client program. |
|
Program: A typical problem: A class method that accesses instance variables. |
|
Read more about class methods in the text book version of this material. |
Static Classes and Partial Classes in C# Slide Annotated slide Contents Index References Textbook | If you have a class with only class variables and class methods (only static members), you may chose to mark the class as static. A partial class will be aggregated by contributions from several source files. |
|
|
|
Read more about static classes and partial classes in the text book version of this material. |
Constant and readonly variables Slide Annotated slide Contents Index References Textbook | C# supports constants - marked with const - which are computed and bound at compile time, before the program starts its execution. C# also supports variables - marked with readonly - which can only be assigned when the surrounding object is created. Once the object has been created, these variables are constant (read only) as well. |
|
|
Program: Legal use of constants and readonly variables. |
|
Program: Illegal use of constant and readonly variables. |
|
Read more about constants in the text book version of this material. |
Objects and Classes Slide Annotated slide Contents Index References Textbook | You are supposed to know the difference between a class and an object. This difference is explained on this page. |
|
|
|
Read more about classes vs. objects in the text book version of this material. |
The current object - this Slide Annotated slide Contents Index References Textbook | The latest receiver of a message is called the current object. This is the object on which the latest instance method has been called. |
|
Program: The BankAccount - emphasizing this. This example shows two different uses of this. First, it may be necessary
to get access to the current object as such. In the example it is necessary
to add the current account to a list of accounts. The second use pertain
to methods (and constructors). It is convenient to use the same name for both formal
parameters of methods and instance variables of the surrounding class. To disambiguate
these, this.x refers to the instance variable named x, and x refers to
the local meaning of x. |
|
Program: The BankAccount - A more radical use of this. In this example, any use of a member of the current object is prefixed with this.
This is a more radical use of this, which highlights use of members in the current object
in contrast to members in other objects.
|
|
|
|
Read more about the current object in the text book version of this material. |
Visibility Issues Slide Annotated slide Contents Index References Textbook | A type has a certain visibility in the namespace to which the type belongs. Similarly, a member of of type has a certain visibility. You can state the visibility explicitly by giving a so-called visibility modifier, or you can rely on defaults. It is recommended always to use explicit visibility modifiers, because it reflects that you have made a conscious choice. |
|
|
Program: An illustration of the 'Inconsistent Accessibility' problem. |
|
Program: Solution to the problem. |
|
Read more about visibility issues - in particular 'inconsistent accessibility' - in the text book version of this material. |
Creating and Deleting Objects |
Creating and Deleting Objects Slide Annotated slide Contents Index References Textbook | On this page we outline possible ways to create and get rid of objects. Notice that all these possibilities are not necessarily supported in your favorite object-oriented programming language, such as C# or Java. |
|
|
|
Read more about creating and deleting objects in the text book version of this material. |
Instantiation of classes Slide Annotated slide Contents Index References Textbook | We now focus on a particular way of object creation, namely instantiation of classes. There are - in principle - two approaches that can be used. Again, it should be emphasized that both approaches are not necessarily supported in a given programming language. |
The concept instantiation: Instantiation is the process of allocating memory to a new object of some class |
|
On the next page we will see that C# relies on dynamic instantiation. |
Instantiation of classes in C# Slide Annotated slide Contents Index References Textbook | C# uses the new operation for dynamic instantiation of classes. Static instantiation cannot be used for classes in C#. As we will see later, static instantiation is used for stucts. |
|
Program: The class Point. |
|
Program: Use of the class Point in a client class called Application. |
|
Program: Output from the Point client program. |
|
Read more about instantiation of classes in the text book version of this material. |
Initialization of objects Slide Annotated slide Contents Index References Textbook | The step after instantiation is called initialization. Without initialization, the memory of the allocated object may contain random values. In this context, random values is the same as garbage! In order to avoid this, a new object should always be initialized. In C#, constructors are responsible for initialization of the instance variables. |
The concept initialization: Initialization is the process of ascribing initial values to the instance variables of an object |
Do not rely on default values! It is recommended that you bundle all initializations of instance variables in constructors. |
|
Read more about initialization in the text book version of this material. |
Constructors in C# Slide Annotated slide Contents Index References Textbook | You should strive to organize initialization of all instance variables in constructors. |
The concept constructor: A constructor is a special method which is called automatically in order to initialize a new instance of a class |
|
Program: Constructors in class BankAccount. The naive implementation of three constructors. |
|
Program: Improved constructors in class BankAccount. A much better implementation of the three constructors. |
|
Program: Constructors in the class Die. Two constructors in class Die. One constructor uses the other (general) constructor. |
|
Read more about constructors in C# in the text book version of this material. |
Copy constructors Slide Annotated slide Contents Index References Textbook | The easy way to program object copying is via copy constructors. A copy constructor takes a single parameter of the same type as the surrounding class. |
|
Program: The class Die with a copy constructor. |
|
|
|
Read more about Copy constructors in the text book version of this material. |
Initialization of class variables Slide Annotated slide Contents Index References Textbook | Constructors are deserved for initialization of instance variables. Class variable should be initialized before initialization of any instance variable. |
|
In most cases, we rely on initializers for initialization of class variables. In some rare situations we need the power of static constructors. An example is shown below. |
Program: The class PlayingCard with a static constructor. |
|
Program: A client of class PlayingCard. |
|
Program: Output from the PlayingCard client program. |
|
Read more about initialization of class variables in the text book version of this material. |
Chapter 3: Classes and Objects
Course home Author home About producing this web Previous lecture (top) Next lecture (top) Previous lecture (bund) Next lecture (bund)
Generated: February 7, 2011, 12:13:12