31
©The McGraw-Hill Companies, 2006 Chapter 6 Classes and objects

Chapter 6staff.unak.is/andy/Java20809/Lectures/pp_ch06.pdf · • in Java, String is a class - predefined by the people who developed the Java language; • when we create new strings,

  • Upload
    dangtu

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

©The McGraw-Hill Companies, 2006

Chapter 6

Classes and objects

©The McGraw-Hill Companies, 2006

Structured programming

• structured programming was the first attempt at formally modularizing program code;

• now the program was no longer considered one large task, but a collection of smaller tasks;

• these tasks were called procedures or functions in older programming languages, but methods in object-oriented languages;

• in chapter 4 we effectively used a structured approach.

• the diagram below illustrates this for a more complex situation;

• here the top-level method is broken down into four tasks;

• the second task is broken down further into two tasks, and so on.

©The McGraw-Hill Companies, 2006

©The McGraw-Hill Companies, 2006

Example

• in program 4.8 the main method called three other methods - option1, option2 and option3.

• for some time this approach to modular design dealt adequately with the increased complexity of software;

• with the rapid microchip advances of the 1980s and the growth of the Internet in the 1990s, the demands on software developers increased again and the structured approach was found to be deficient;

• the reason for this is that the approach focuses on the actions (methods) but not the things acted on – the data;

• the data becomes spread throughout the system in a very unstructured way (see below):

©The McGraw-Hill Companies, 2006

©The McGraw-Hill Companies, 2006

The above approach can lead to

the following problems:

data is subject to change by many methods, and data can therefore become unexpectedly corrupted, leading to unreliable programs that are difficult to debug;

revising the data requires rewriting every method that interacts with it, leading to programs that are very difficult to maintain;

methods and the data they act upon are not closely tied together, leading to code that is very difficult to reuse since there is a complex web of links to disentangle.

©The McGraw-Hill Companies, 2006

The object-oriented solution

• consider a program that would be suitable for a college or university for the administration of students and courses;

• it would have to store information about students, such as their personal details, their marks and so on;

• it would have to perform tasks such as adding students, updating students' marks etc;

• it would need to store information about the courses on offer and the cost of the course;

• it would need to provide methods to update course information, add and remove courses and perform many other tasks;

• in some cases these methods would need information about both students and courses.

• with the "old-fashioned" structured approach, all the data about students and courses would be stored as part of one big program.

• in the object-oriented approach, methods and the data they act upon are grouped together into one unit;

• this higher unit of organization is called an object (see below).

©The McGraw-Hill Companies, 2006

©The McGraw-Hill Companies, 2006

Classes

• a class is the blueprint from which objects are generated;

• if we have six students in our university administration system, we do not need to define a student six times;

• we define a student once (in a class) and then generate as many objects as we want from this blueprint;

• in one program we may have many classes, as we would probably wish to generate many kinds of objects (students, courses, lecturers etc.).

• object-oriented programming therefore consists of defining one or more classes that may interact with each other;

• to exploit the full power of object-orientation requires us to use an object-oriented programming language e.g: C++, SmallTalk, Eiffel, C#, Java.

©The McGraw-Hill Companies, 2006

Classes as data types

• simple data types such as char, int and double hold a single piece of information;

• you have already been using the String "type";

• in Java, String is a class - predefined by the people who developed the Java language;

• when we create new strings, we are creating objects of the String class;

• with an object-oriented programming language such as Java, it is possible to manipulate not just simple types, but objects of a class.

©The McGraw-Hill Companies, 2006

Attributes and methods

• there are two aspects to a class:– the data that is holds;

– the tasks it can perform.

• the items of data that a class holds are referred to as the attributes of the class;

• the tasks it can perform are referred to as the methodsof the class.

• only methods that are allowed access to the data are the methods of the class itself;

• in the object-oriented approach, methods of one class are normally denied direct access to the data of another class, thus making it a lot more difficult to corrupt the data;

• this principle is known as encapsulation or information-hiding.

©The McGraw-Hill Companies, 2006

The Oblong class

©The McGraw-Hill Companies, 2006

Constructors• this always has the same name as the class;

• when you create a new object this special method is always called;

• its function is to reserve some space in the computer's memory just big enough to hold the required object;

• the person developing the class doesn't have to worry about defining the constructor if this is all that he or she wants the constructor to do;

• it is very common to find that you want the constructor to do more than this when a new object is created;

• a constructor can be overloaded, so we can create constructors of our own;

• in the case of the Oblong class, the constructor has been defined so that every time a new Oblong object is created the length and the height are set;

• they are set to the values that the user of the class sends in;

• every time you create an Oblong you have to specify its length and its height at the same time.

©The McGraw-Hill Companies, 2006

Using the Oblong class

• program 6.1 shows how the Oblong class can be used by

another class, in this case a class called OblongTester.

Analysis if the main method

• this method declares two variables:

• these are going to hold the value that the user chooses for

the length and height of the oblong.

©The McGraw-Hill Companies, 2006

• the next line declares a reference to an Oblong:

• this line is similar to a declaration of a variable;

• it creates a variable that can hold a reference;

• as explained in the previous chapter, a reference is simply

a name for a location in memory;

• at this stage we have not reserved space for the new

Oblong object;

• all we have done is named a memory location myOblong

©The McGraw-Hill Companies, 2006

• the next lines:

– prompt the user to enter a value for the length of the

oblong;

– read the user's chosen value from the keyboard;

– do the same thing for the height.

• the values entered are stored in oblongLength and

oblongHeight respectively:

©The McGraw-Hill Companies, 2006

What is going to be held in the

memory location called myOblong?

• consider the following line:

• this statement that reserves space in memory for a new Oblong object;

• as arrays, this is done by using the keyword new, in conjunction with the name of the class (in this case Oblong) and some parameters in the brackets;

• using the class name in this way, with the keyword new, calls the constructor;

• memory is reserved for a new Oblong object;

• in the case of the Oblong class we defined our own constructor method;

• this method requires that two items of data get sent in, both of type double.

• the location of the new object is stored in the named location myOblong.

©The McGraw-Hill Companies, 2006

The null value

• in Java, when a reference is first created it is given a special value of

null;

– a null value indicates that no storage is allocated;

– we can also assign a null value to reference at any point in the

program, and test for it.

– for example:

©The McGraw-Hill Companies, 2006

Calling a method of one class

from a method of another class

• consider the following line of program 6.1:

• this line displays the length of the oblong;

• it uses the method of Oblong called getLength;

• we are calling a method of one class (the getLength method of Oblong) from within a method of another class (the main method of OblongTester);

• to do this we use the name of the object (in this case myOblong) together with the name of the method (getLength) separated by a full stop (often referred to as the dot operator);

• you have seen this already with the methods of the Scanner class.

©The McGraw-Hill Companies, 2006

The keyword this • in chapter 4, when we called the methods from within a class,

we used the name of the method on its own;

• in fact, what we were doing is form of shorthand.

• When we write a line such as

• we are actually saying:– call demoMethod, which is a method of this class.

• in Java there exists a special keyword this;

• the keyword this is used within a class when we wish to refer to an object of the class itself, rather than an object of some other class;

• the line of code above is actually shorthand for:

©The McGraw-Hill Companies, 2006

©The McGraw-Hill Companies, 2006

Comparing strings

• when comparing two objects, such as Strings, we should do so

by using a method called equals;

• we should not use the equality operator (==);

• this should be used for comparing primitive types only.

Example

• if we had declared two strings, firstString and secondString, we

would compare these in, say, an if statement as follows;

• using the equality operator (==) to compare strings is a very

common mistake that is made by programmer;

©The McGraw-Hill Companies, 2006

Using the compareTo method -

consider program 6.3

Sample run:

• Enter a String: hello

• Enter another String: goodbye

• goodbye comes before hello in the alphabet

• compareTo is case-sensitive - upper case letters will be considered as coming before lower-case letters (their Unicode value is lower);

• if you are not interested in the case of the letters, you should convert both strings to upper (or lower) case before comparing them.

• if all you are interested in is whether the strings are identical, it is easier to use the equals method;

• if the case of the letters is not significant you can use equalsIgnoreCase.

©The McGraw-Hill Companies, 2006

Our own Scanner class for keyboard

input

Issues with using the Scanner class for keyboard input

• it is necessary to create a new Scanner object in every method that uses the Scanner class;

• there is no simple method such as nextChar for getting a single character like there is for the int and doubletypes;

• the next method doesn't allow us to enter strings containing spaces.– there is a nextLine method that does return the whole string that

is entered, including spaces;

– however, if the nextLine method is used after a nextInt or nextDouble method, then it is necessary to create a new Scanner object (because using the same Scanner object will make your program behave erratically).

©The McGraw-Hill Companies, 2006

• to make life easier, we have created a new class

which we have called EasyScanner;

©The McGraw-Hill Companies, 2006

©The McGraw-Hill Companies, 2006

The BankAccount class

©The McGraw-Hill Companies, 2006

• the output from this program is:

Account number: 99786754

Account name: Susan Richards

Current balance: 1000.0

©The McGraw-Hill Companies, 2006

Arrays of objects

Consider program 6.6

• the first line of the main method looks the same as the

declaration and creation of an array of primitive types:

• however, what is actually going on behind the scenes is

slightly different;

• the above statement does not set up an array of

BankAccount objects in memory;

• instead it sets up an array of references to such objects.

©The McGraw-Hill Companies, 2006

• at the moment, space has been reserved for the three

BankAccount references only, not the three BankAccount

objects;

• when a reference is initially created it points to the

constant null, so at this point each reference in the array

points to null.

• memory would still need to be reserved for individual

BankAccount objects each time we wish to link a

BankAccount object to the array;

• we can create new BankAccount objects and associate

them with elements in the array:

©The McGraw-Hill Companies, 2006

Once we have created these accounts, we make some deposits and withdrawals.

The output

Account number: 99786754

Account name: Susan Richards

Current balance: 500.0

Account number: 44567109

Account name: Delroy Jacobs

Current balance: 0.0

Account number: 46376205

Account name: Sumana Khan

Current balance: 150.0