ppt - Mathematical & Computer Sciences

advertisement
F21SF
Software Engineering Foundations
L3 Strings
More Class Design with a Name class
String methods
Dept of
Computer
Science
13/04/2015
Monica Farrow EM G30
email : M.Farrow@hw.ac.uk
Material available on Vision
SJF L3
1
Topics


Another example of a class, to hold name
information
More object-oriented concepts






Accessor and mutator methods (get/set)
Information hiding
Classes as instance variables
Testing a class with a main method
Char data type
String methods and the java API
13/04/2015
SJF L3
2
Names


A person’s name may consist of a first name,
middle name, last name. We’re just considering
British names here.
The name could be required in lots of different
formats. E.g.






Smith, Mary Ann
M. A. Smith
MAS
Mary Smith
Etc etc
We’d like a class to hold the data and supply the
name in various formats
13/04/2015
SJF L3
3
Recap - A class consists of


A name, which should start in upper case e.g. Car
Instance variables to describe the data about a
particular object


A constructor, to create the object and assign
values to the instance variables


Eg. Model, tank size etc
E.g. tankSize = 66
Methods, to perform operations on the data.
These are similar to functions and subroutines in
other languages


E.g. find out how far the car can travel
E.g. tell us what the tank size is
13/04/2015
SJF L3
4
Outline UML Class diagram
Name
Main
main(..)
first name
middle name
last name
create name with initial data
return the first name
return the middle name
return the last name
return the first name, a space,
and the last name
return the last name, comma, space,
first name and middle name
etc
13/04/2015
SJF L3
5
Outline UML sequence diagram
Standard
output
main()
Create a name
myName
:Name
Get the name in required format
Use standard output to display results
Repeat the last 2 method calls as often as required.
13/04/2015
SJF L3
6
Class outline
public class Classname
{
//instance variables
//constructor(s)
//methods
}
So a Car class starts
public class Car
So a Name class starts
public class Name
13/04/2015
SJF L3
7
Designing a Name class - 1

First we define the instance variables



Access modifier, always private
Type e.g. int, String, double
Identifier i.e. meaningful name starting lower case
private String firstName;
private String middleName;
private String lastName;
13/04/2015
SJF L3
8
Designing a Name class - 2

Constructor

With parameters giving values which are then allocated
to instance variables
public Name(String fName, String mName, String lName)
{
firstName = fName;
middleName = mName;
lastName = lName;
}

using the constructor in another class:
Name person = new Name("Keith", "David", "Black");
13/04/2015
SJF L3
9
Initial values of instance variables



When we declare instance variables, we are giving a name
and type to the variable which will be used to contain the
values for a particular object.
These values are assigned when the constructor is called
Either by:

Using values supplied as parameters


Setting the value to a suitable default or initial value


E.g. tankSize = tank;
E.g. hours = 0;
If (usually by mistake) we don’t store a value in an
instance variable,


Primitive types such as ‘int’ will contain 0.
Class types, such as ‘String’, will not contain details of an object.
They are said to be ‘null’.
13/04/2015
SJF L3
10
Methods

Some methods provide (return) information for
use within another method. They have a return
type.


Some methods do something, without returning
any information


E.g. get car model, get estimated distance
E.g. printing details
System.out.println ("Hello");
Methods may have parameters which affect
their behaviour.

E.g. what to print, the parameters in the Constructor
13/04/2015
SJF L3
11
Data privacy – information hiding




Object specific data (e.g. tank size, first name) is stored in
instance variables which should usually be declared
private.
Then the only way that another class can access the
instance variables is by using a public method which
returns the value.
The details of how the data is stored is not required by
another class
This means that internal modifications could be made to a
class. As long as the original public methods stay
unchanged, other classes are not affected.
13/04/2015
SJF L3
12
Accessor / get methods

‘accessor’ or ‘get’ methods are public methods
which return the values stored in the instance
variables. These conventionally start with the
word ‘get’


getModel() in Car class
Often, a programmer will write ‘get’ methods for
all the instance variables
13/04/2015
SJF L3
13
Get methods for the Name class

One for each instance variable:
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
13/04/2015
SJF L3
14
More methods which return values


In the methods below, new Strings are formed by
‘concatenating’ other Strings, using the +
operator
To return the first and last name e.g. Mary Smith
public String getFirstAndLastName()
{ return firstName + " " + lastName; }

To return the surname, comma, space and first
name
e.g. Smith, Mary
public String getLastCommaFirst()
{ return lastName + ", " + firstName; }
13/04/2015
SJF L3
15
Using/testing the Name class

Here is a main method to use the Name class and
print out some details

By attaching the method call to a specific object (e.g.
name1), the method uses the values stored in the
instance variables of that particular object.
public class UseName {
public static void main(String[] args) {
Name name1 = new Name ("Mary", "Ann", "Smith");
System.out.print("First name and last name : " );
System.out.println(name1.getFirstAndLastName() );
System.out.print("Surname, comma, firstname : ");
System.out.println(name1.getLastCommaFirst());
}
}
13/04/2015
SJF L3
16
QUIZ


Are there any lines here which prevent the program from
compiling successfully?
What would be printed by lines which are correct?
public class NameQuiz {
public static void main(String[] args) {
1. Name name1 = new Name ("Mary", "Ann", "Smith");
2. Name name2 = new Name ("John", "James",
"Thomson");
3. System.out.print(name1.getFirstName());
4. System.out.println(name2.getLastName());
5. System.out.println (name1.getFirstAndLastName() );
6. System.out.println(name2.getLastCommaFirst());
7. System.out.println(name1.getFirstMiddleLast());
8. System.out.println(name3.getFirstName());
}
SJF L3
17
} 13/04/2015
Mutator / set methods



Sometimes we’d like to be able to change the
values in the instance variables after the
constructor has been used
Methods that change instance variables are often
called ‘mutator’ or ‘set’ methods and start with
the word ‘set’
Often, a programmer will write ‘set’ methods for
all the instance variables
13/04/2015
SJF L3
18
Changing a last name (1)

To change a last name, include a ‘set’ method in
the Name class
Return type is void
 The parameter provides the new name
 The statement in the method body alters the instance
variable
public void setLastName(String newName) {
lastName = newName;
}

13/04/2015
SJF L3
19
Changing a last name (2)

Testing this in a main method
Name myName = new Name("Jane","Jo", "Jones");
Name otherName = new Name("John","Tom", "Kerr");
String last = myName.getLastName();
System.out.println(last);
String newname = otherName.getLastName();
myName.setLastName(newname);
String newLast = myName.getLastName();
System.out.println(newLast);
//you don’t always have to put the item to be
printed into a local variable
System.out.println(myName.getFirstAndLastName());
13/04/2015
SJF L3
20
INTRODUCING
STRINGS
13/04/2015
SJF L3
21
char data type

The char data type is used to represent a single
character from the character set




letters, digits i.e. A…Z, a..z, 0..9
other printable characters e.g. !"£$%^
'special' characters e.g. tab, new line…….
characters are represented in the computer by a
number code


UNICODE for java, allows 65536 characters
ASCII used in many languages 128 characters
13/04/2015
SJF L3
22
Character values

A char literal is enclosed with a single quote


'A', '?', '9' (NB space ' ' is a character)
To declare and initialise a character variable:


char myChar = '?';
You choose the most appropriate data type:

Use a number if you’re going to use arithmetic operations



An int is simplest: int num = 5;
A double if the contents might not be integers:
double number = 5; (or 5.0)
Use a String or a char if it will always just be text, and no
calculations are needed (e.g. phone number, matric number)


String myText = "5";
char ch = '5';
13/04/2015
SJF L3
23
Overloading the + operator (1)

The + operator is used in java to



3 + 4 -> 7
“5” + “Hello” -> “5Hello”
Concatenation is used when there is a String on
one side



Add numbers
Concatenate Strings
5 + “Hello” -> “5Hello”
‘5’ + “Hello” -> “5Hello”
What about



5 + 4 -> 9
5 + “4” -> 54 (String concatenation)
5 + ‘4’ -> 57 (why? See next slide)
13/04/2015
SJF L3
24
Overloading the + operator (2)

‘A’ + ‘B’ + ‘C’ -> 198


Adding just characters actually adds the numeric values
of the characters. Here the ‘+’ sign is interpreted to
mean add the underlying integer values, which for ‘A’ is
65, ‘B’ is 66 etc
“” + ‘A’ + ‘B’ + ‘C’ -> “ABC”.




This expression is evaluated from left to right.
There is a String first, so the first + operator produces
a String “A”
The second + operator then has String “A” on the LHS,
so produces “AB”.
The 3rd + operator has String “AB” on the LHS, so
produces “ABC”
13/04/2015
SJF L3
25
The API



Java itself is a small language
To program in Java, you need to use the Java API
(Application Programming Interface) which
consists of sets of useful classes.
The API is divided into packages




The most commonly used classes are in java.lang and
can be used by all other classes without any extra
considerations
A package contains a group of related classes
Every class in the API is documented
One such class in the java.lang package is the
String class
13/04/2015
SJF L3
26
Strings




String is a class in Java
Strings are so basic that you don’t have to
instantiate them explicitly
We can write
String name = "Cathy";
We don’t have to write (though we could)
String name = new String("Cathy");
13/04/2015
SJF L3
27
How to picture a string


The number of characters in a String is known as
its length
Each individual character in a String has a known
position located by an index, indexing starts at 0
and goes up to length-1
String myName = "Barbara";
B
0
13/04/2015
a
1
r b a r a
2 3 4 5 6
7
SJF L3
28
Class documentation

The complete specification can be found at
http://download.oracle.com/javase/7/docs/api/


The documentation will show the class’s interface:





Search for your class on the left hand side
the name of the class
a general description of the class and its use
a list of methods, with parameters and return types
a description of what each method does
The documentation does NOT include HOW the method
works, you don’t need to know this, only how to use it.
13/04/2015
SJF L3
29
String methods



You think what you want your code to do
You look through the API to see if any method is
likely to help
For example, if you want to get the first character
of a name (the initial)


You find the String method charAt(int index)
which returns the character in position given by ‘index’
The code below returns the first character
char initial = firstName.charAt(0);
13/04/2015
SJF L3
30
Java documentation

Here is the documentation on the charAt method:
Method name
and link to
slightly fuller
description
Parameters incl type
charAt(int index)
char
Returns the char value at the specified index.
Return type
13/04/2015
Description
SJF L3
31
Other methods - exercise

Look at the java API for the String class and find
out how to:





Discover if a certain group of letters “and” is anywhere
in the String s
Discover if the String s starts with “Mac”
Convert the contents of String s to upper case
Find out how long is String s?
Get the last character of String s?
13/04/2015
SJF L3
32
Getting an initial

We can now write a method in the Name class to
return the name in the format initial, period,
space, last name
E.g. M. Smith.
public String getInitPeriodLast() {
return firstName.charAt(0)
+ ".
"
+
lastName;
}
13/04/2015
SJF L3
33
UML sequence diagram
main()
Create a name
n2:Name
firstname
:String
Get first and last name
Get last, comma, first
Get initial, period, last
Get char at 0
Not all
methods
shown.
13/04/2015
F21SF SEF L2
34
Summary

We now have a Name class which



A class has





Provides another example of a class
Uses Strings and methods of the String class
Instance variables
A constructor
Get and set methods for the instance variables
Other useful methods
Next, we have another look at the Car class, and
more OOP concepts
13/04/2015
SJF L3
35
To Do - code


Using eclipse, type up the Name class and the class with the main
method. Correct typing errors, run and check it works as expected.
Try calling a few other methods.
Write another class to hold details of a bank account:

Data




An account number – 6 digits e.g. 039864
How much money is in the account – a balance e.g. 120.56
How much overdraft is permitted e.g. 1000
Methods



To ‘get’ each instance variable
To ‘set’ each instance variable
To return how much money could be taken out



(this is the overdraft plus the balance)
Write a main method which creates an account and uses some of the
methods
What other methods are likely to be useful in an Account class?
13/04/2015
SJF L3
36
To Do - Diagrams

Draw a class diagram for the name class


See diagram for Car class towards end of lecture 2
Draw a sequence diagram for the main method in
the previous slide ‘changing a last name(2)’
13/04/2015
SJF L3
37
Download