Docsity

Creating Custom Objects in Java: Defining a Time Class, Assignments of Computer Science

Toggle sidebar
bg1
Chapter 10
Create your own objects
10.1 Class definitions and object types
In this chapter we will write class definitions that create new Java object types.
The most important ideas in this chapter are
•Defining a new class also creates a new object type with the same name.
•A class definition is like a template for objects: it determines what instance
variables the objects have and what methods can operate on them.
•Every object belongs to some object type; hence, it is an instance of some
class.
•When you invoke the new command to create an object, Java invokes a
special method called a constructor to initialize the instance variables.
You provide one or more constructors as part of the class definition.
•Typically all the methods that operate on a type go in the class definition
for that type.
Here are some syntax issues about class definitions:
•Class names (and hence object types) always begin with a capital letter,
which helps distinguish them from primitive types and variable names.
•You usually put one class definition in each file, and the name of the file
must be the same as the name of the class, with the suffix .java. For
example, the Time class is defined in the file named Time.java.
•In any program, one class is designated as the startup class. The startup
class must contain a method named main, which is where the execution of
the program begins. Another class may have a method named main, but
it will not be executed.
With those issues out of the way, let’s look at an example of a user-defined
type, Time.
91
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Creating Custom Objects in Java: Defining a Time Class and more Assignments Computer Science in PDF only on Docsity!

Chapter 10

Create your own objects

10.1 Class definitions and object types

In this chapter we will write class definitions that create new Java object types. The most important ideas in this chapter are

  • Defining a new class also creates a new object type with the same name.
  • A class definition is like a template for objects: it determines what instance variables the objects have and what methods can operate on them.
  • Every object belongs to some object type; hence, it is an instance of some class.
  • When you invoke the new command to create an object, Java invokes a special method called a constructor to initialize the instance variables. You provide one or more constructors as part of the class definition.
  • Typically all the methods that operate on a type go in the class definition for that type. Here are some syntax issues about class definitions:
  • Class names (and hence object types) always begin with a capital letter, which helps distinguish them from primitive types and variable names.
  • You usually put one class definition in each file, and the name of the file must be the same as the name of the class, with the suffix .java. For example, the Time class is defined in the file named Time.java.
  • In any program, one class is designated as the startup class. The startup class must contain a method named main, which is where the execution of the program begins. Another class may have a method named main, but it will not be executed. With those issues out of the way, let’s look at an example of a user-defined type, Time.

92 CHAPTER 10. CREATE YOUR OWN OBJECTS

10.2 Time

A common motivation for creating a new Object type is to take several related pieces of data and encapsulate them into an object that can be manipulated (passed as an argument, operated on) as a single unit. We have already seen two built-in types like this, Point and Rectangle. Another example, which we will implement ourselves, is Time, which is used to record the time of day. The various pieces of information that form a time are the hour, minute and second. Because every Time object will contain these data, we need to create instance variables to hold them. The first step is to decide what type each variable should be. It seems clear that hour and minute should be integers. Just to keep things interesting, let’s make second a double, so we can record fractions of a second. Instance variables are declared at the beginning of the class definition, out- side of any method definition, like this:

class Time { int hour, minute; double second; }

All by itself, this code fragment is a legal class definition. The state diagram for a Time object would look like this:

0

hour 0

minute

second

After declaring the instance variables, the next step is usually to define a constructor for the new class.

10.3 Constructors

The usual role of a constructor is to initialize the instance variables. The syntax for constructors is similar to that of other methods, with three exceptions:

  • The name of the constructor is the same as the name of the class.
  • Constructors have no return type and no return value.
  • The keyword static is omitted.

94 CHAPTER 10. CREATE YOUR OWN OBJECTS

So far this might not seem very interesting, and in fact it is not. Writing constructors is a boring, mechanical process. Once you have written two, you will find that you can churn them out in your sleep, just by looking at the list of instance variables.

10.5 Creating a new object

Although constructors look like methods, you never invoke them directly. In- stead, when you use the new command, the system allocates space for the new object and then invokes your constructor to initialize the instance variables. The following program demonstrates two ways to create and initialize Time objects:

class Time { int hour, minute; double second;

public Time () { this.hour = 0; this.minute = 0; this.second = 0.0; }

public Time (int hour, int minute, double second) { this.hour = hour; this.minute = minute; this.second = second; }

public static void main (String[] args) {

// one way to create and initialize a Time object Time t1 = new Time (); t1.hour = 11; t1.minute = 8; t1.second = 3.14159; System.out.println (t1);

// another way to do the same thing Time t2 = new Time (11, 8, 3.14159); System.out.println (t2); } }

As an exercise, figure out the flow of execution through this program.

10.6. PRINTING AN OBJECT 95

In main, the first time we invoke the new command, we provide no arguments, so Java invokes the first constructor. The next few lines assign values to each of the instance variables. The second time we invoke the new command, we provide arguments that match the parameters of the second constructor. This way of initializing the instance variables is more concise (and slightly more efficient), but it can be harder to read, since it is not as clear which values are assigned to which instance variables.

10.6 Printing an object

The output of the previous program is:

Time@80cc7c Time@80cc

When Java prints the value of a user-defined object type, it prints the name of the type and a special hexadecimal (base 16) code that is unique for each object. This code is not meaningful in itself; in fact, it can vary from machine to machine and even from run to run. But it can be useful for debugging, in case you want to keep track of individual objects. In order to print objects in a way that is more meaningful to users you should provide a method named toString that returns a String representation of the object. When you print an object using print or println, Java checks to see whether you have provided toString, and if so it invokes it. If not, it invokes a default version of toString that produces the output we just saw.

public String toString () { return hour + ":" + minute + ":" + second; }

The output of this method, if we print either t1 or t2, is 11:8:3.14159. Al- though this is recognizable as a time, it is not quite in the standard format. For example, if the number of minutes or seconds is less than 10, we expect a leading 0 as a place-keeper. Also, we might want to drop the decimal part of the seconds. In other words, we want something like 11:08:03. In most languages, there are simple ways to control the output format for numbers. In Java there are no simple ways. Java provides very powerful tools for printing formatted things like times and dates, and also for interpreting formatted input. Unfortunately, these tools are not very easy to use, so I am going to leave them out of this book. If you want, though, you can take a look at the documentation for the Date class in the java.util package.

10.8. PURE FUNCTIONS 97

sum.minute = minute + t2.minute; sum.second = second + t2.second; return sum; }

Although this method returns a Time object, it is not a constructor. You should go back and compare the syntax of a method like this with the syntax of a constructor, because it is easy to get confused. Here is an example of how to use this method. If currentTime contains the current time and breadTime contains the amount of time it takes for your breadmaker to make bread, then you could use addTime to figure out when the bread will be done.

Time currentTime = new Time (9, 14, 30.0); Time breadTime = new Time (3, 35, 0.0); Time doneTime = currentTime.add (breadTime); printTime (doneTime);

The output of this program is 12:49:30.0, which is correct. On the other hand, there are cases where the result is not correct. Can you think of one? The problem is that this method does not deal with cases where the number of seconds or minutes adds up to more than 60. In that case, we have to “carry” the extra seconds into the minutes column, or extra minutes into the hours column. Here’s a second, corrected version of this method.

public Time add (Time t2) { Time sum = new Time (); sum.hour = hour + t2.hour; sum.minute = minute + t2.minute; sum.second = second + t2.second;

if (sum.second >= 60.0) { sum.second -= 60.0; sum.minute += 1; } if (sum.minute >= 60) { sum.minute -= 60; sum.hour += 1; } return sum; }

Although this version is correct, it’s starting to get big. Later, I will suggest an alternate approach to this problem that will be much shorter. This code demonstrates two operators we have not seen before, += and -=. These operators provide a concise way to increment and decrement variables.

98 CHAPTER 10. CREATE YOUR OWN OBJECTS

They are similar to ++ and --, except (1) they work on doubles as well as ints, and (2) the amount of the increment does not have to be 1. The statement sum.second -= 60.0; is equivalent to sum.second = sum.second - 60;

10.9 Modifiers

As an example of a modifier, consider increment, which adds a given number of seconds to a Time object. Again, a rough draft of this method looks like:

public void increment (double secs) { second += secs;

if (second >= 60.0) { second -= 60.0; minute += 1; } if (minute >= 60) { minute -= 60; hour += 1; } }

The first line performs the basic operation; the remainder deals with the same cases we saw before. Is this method correct? What happens if the argument secs is much greater than 60? In that case, it is not enough to subtract 60 once; we have to keep doing it until second is below 60. We can do that by simply replacing the if statements with while statements:

public void increment (double secs) { second += secs;

while (second >= 60.0) { second -= 60.0; minute += 1; } while (minute >= 60) { minute -= 60; hour += 1; } }

This solution is correct, but not very efficient. Can you think of a solution that does not require iteration?

100 CHAPTER 10. CREATE YOUR OWN OBJECTS

secs -= this.minute * 60; this.second = secs; }

This constructor is a little different from the others, since it involves some calculation along with assignments to the instance variables. You might have to think a bit to convince yourself that the technique I am using to convert from one base to another is correct. Assuming you are convinced, we can use these methods to rewrite add:

public Time add (Time t2) { double seconds = this.convertToSeconds () + t2.convertToSeconds (); return new Time (seconds); }

This is much shorter than the original version, and it is much easier to demon- strate that it is correct (assuming, as usual, that the methods it invokes are correct). As an exercise, rewrite increment the same way.

10.12 Generalization

In some ways converting from base 60 to base 10 and back is harder than just dealing with times. Base conversion is more abstract; our intuition for dealing with times is better. But if we have the insight to treat times as base 60 numbers, and make the investment of writing the conversion methods (convertToSeconds and the third constructor), we get a program that is shorter, easier to read and debug, and more reliable. It is also easier to add more features later. For example, imagine subtracting two Times to find the duration between them. The naive approach would be to implement subtraction complete with “borrowing.” Using the conversion methods would be much easier. Ironically, sometimes making a problem harder (more general) makes is eas- ier (fewer special cases, fewer opportunities for error).

10.13 Algorithms

When you write a general solution for a class of problems, as opposed to a specific solution to a single problem, you have written an algorithm. I mentioned this word in Chapter 1, but did not define it carefully. It is not easy to define, so I will try a couple of approaches. First, consider some things that are not algorithms. For example, when you learned to multiply single-digit numbers, you probably memorized the multipli- cation table. In effect, you memorized 100 specific solutions, so that knowledge is not really algorithmic.

10.14. GLOSSARY 101

But if you were “lazy,” you probably cheated by learning a few tricks. For example, to find the product of n and 9, you can write n − 1 as the first digit and 10 − n as the second digit. This trick a general solution for multiplying any single-digit number by 9. That’s an algorithm! Similarly, the techniques you learned for addition with carrying, subtraction with borrowing, and long division are all algorithms. One of the characteristics of algorithms is that they do not require any intelligence to carry out. They are mechanical processes in which each step follows from the last according to a simple set of rules. In my opinion, it is embarrassing that humans spend so much time in school learning to execute algorithms that, quite literally, require no intelligence. On the other hand, the process of designing algorithms is interesting, intel- lectually challenging, and a central part of what we call programming. Some of the things that people do naturally, without difficulty or conscious thought, are the most difficult to express algorithmically. Understanding natural language is a good example. We all do it, but so far no one has been able to explain how we do it, at least not in the form of an algorithm. Later you will have the opportunity to design simple algorithms for a variety of problems.

10.14 Glossary

class: Previously, I defined a class as a collection of related methods. In this chapter we learned that a class definition is also a template for a new type of object.

instance: A member of a class. Every object is an instance of some class.

constructor: A special method that initializes the instance variables of a newly-constructed object.

project: A collection of one or more class definitions (one per file) that make up a program.

startup class: The class that contains the main method where execution of the program begins.

function: A method whose result depends only on its parameters, and that has no side-effects other than returning a value.

functional programming style: A style of program design in which the ma- jority of methods are functions.

modifier: A method that changes one or more of the objects it receives as parameters, and usually returns void.

algorithm: A set of instructions for solving a class of problems by a mechanical, unintelligent process.