380 likes | 557 Views
L3 Strings More Class Design with a Name class String methods. Dept of Computer Science. F21SF Software Engineering Foundations. Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision. Topics. Another example of a class, to hold name information
E N D
SJF L3 L3 Strings More Class Design with a Name class String methods Dept of Computer Science F21SFSoftware Engineering Foundations Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision
SJF L3 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
SJF L3 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
SJF L3 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 • Eg. Model, tank size etc • A constructor, to create the object and assign values to the instance variables • 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
SJF L3 Outline UML Class diagram Name 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 Main main(..)
SJF L3 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.
SJF L3 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
SJF L3 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;
SJF L3 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");
SJF L3 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 • E.g. tankSize = tank; • Setting the value to a suitable default or initial value • 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’.
SJF L3 Methods • Some methods provide (return) information for use within another method. They have a return type. • E.g. get car model, get estimated distance • Some methods do something, without returning any information • 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
SJF L3 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.
SJF L3 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
SJF L3 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;}
SJF L3 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; }
SJF L3 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()); } }
SJF L3 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) { • Name name1 = new Name ("Mary", "Ann", "Smith"); • Name name2 = new Name ("John", "James", "Thomson"); • System.out.print(name1.getFirstName()); • System.out.println(name2.getLastName()); • System.out.println (name1.getFirstAndLastName() ); • System.out.println(name2.getLastCommaFirst()); • System.out.println(name1.getFirstMiddleLast()); • System.out.println(name3.getFirstName()); } }
SJF L3 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
SJF L3 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; }
SJF L3 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());
SJF L3 INTRODUCING STRINGS
SJF L3 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
SJF L3 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';
SJF L3 Overloading the + operator (1) • The + operator is used in java to • Add numbers 3 + 4 -> 7 • Concatenate Strings “5” + “Hello” -> “5Hello” • Concatenation is used when there is a String on one side • 5 + “Hello” -> “5Hello” • ‘5’ + “Hello” -> “5Hello” • What about • 5 + 4 -> 9 • 5 + “4” -> 54 (String concatenation) • 5 + ‘4’ -> 57 (why? See next slide)
SJF L3 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”
SJF L3 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
SJF L3 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");
SJF L3 String myName = "Barbara"; B a r b a r a 0 1 2 3 4 5 6 7 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
SJF L3 Class documentation • The complete specification can be found at http://download.oracle.com/javase/7/docs/api/ • Search for your class on the left hand side • The documentation will show the class’s interface: • 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.
SJF L3 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);
SJF L3 Method name and link to slightly fuller description Parameters incl type char charAt(int index) Returns the char value at the specified index. Return type Description Java documentation • Here is the documentation on the charAt method:
SJF L3 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?
SJF L3 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; }
F21SF SEF L2 UML sequence diagram main() firstname:String Create a name n2:Name Get first and last name Get last, comma, first Get initial, period, last Get char at 0 Not all methods shown.
SJF L3 Summary • We now have a Name class which • Provides another example of a class • Uses Strings and methods of the String class • A class has • 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
SJF L3 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?
SJF L3 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)’