MSc IT
Programming Methodology (2)
number
namenumber
namenumber
balance
abbey
namenumber
balance
namenumber
balance
abbey
deposit
abbey
deposit withdraw
abbey
getBalance
deposit withdraw
abbey
getBalance
deposit withdraw
abbey
BankAccount
abbey
BankAccount
abbeyhalifax
BankAccount
Class
abbeyhalifax
Class
objectobject
Classes and objects
Learning objectives
• explain the meaning of the term object-oriented;
• explain the concept of encapsulation;
• explain the terms class and object;
• create objects in Java;
• call the methods of an object;
• Use a number of methods of the String class;
• create and use arrays of objects.
Object-oriented programming…
Classes….
Student
data
methods
Class
objects
?
s1
s2
s3
s4
Student
data
methods
Class
objects
?
s1
s2
s3
s4
Encapsulation:
The hiding of data within a class
How do you create objects from a Class ?
Object creation is a two-step process:
STEP 1:Declare object type.
Student
data
methods
? s1
s1; Student
Class
object
The effect on computer memory of declaring an object……
Student s1 ;
Computer Memory Java Instructions
s1
? Reference variable
Student s1 ;
Computer Memory Java Instructions
s1
null Reference variable
STEP 2:Allocating memory to store the object data!
This is sometimes called instantiating an object!
Student
data
methods
?
Class
s1
objectStudent( )String, String
A constructor method is required to generate object data from a classs1 = new Student ( );“071202”, “Kans”
The effect on computer memory of instantiating an object……
Student s1 ;
Computer Memory Java Instructions
s1
This is the space for the new Student
object
s1 = new Student (“071202”, “Kans”);
null
You can combine steps 1 & 2!
s1Student
s1 = new Student ( “071202”, “Kans”);
; = new Student (”071202”, “Kans”);
You can instantiate many objects from one Class !
Robot
?
moveRight(int)
moveLeft(int)
moveUp(int)
moveDown(int)
Robot( ) int, int
Robot r1;
r1 = new Robot(5, 50);
Robot r2;
r2 = new Robot(10, 2);
Calling the methods of another class….
Robot
?
moveRight(int)
moveLeft(int)
moveUp(int)
moveDown(int)
Robot( ) int, int
Robot r1;
r1 = new Robot(5, 50);
Robot r2;
r2 = new Robot(10, 2);
Robot
?
moveRight(int)
moveLeft(int)
moveUp(int)
moveDown(int)
Robot( ) int, int
Robot r1;
r1 = new Robot(5, 50);
Robot r2;
r2 = new Robot(10, 2);
r1.moveRight(20);
r2.moveDown(25);
Revisiting the Scanner
class ……
To create a Scanner object we call the Scanner constructor:
Scanner sc = new Scanner (System.in);
Scanner methods…..
int x = sc.nextInt();
double y = sc.nextDouble();
char reply = sc.next().charAt(0);
this is a String methodthis is a String object
The String class
The String class is different from all other classes in Java.
We can create String objects without a call to a constructor:
String day = “Wednesday”; new String (“Wednesday”);
To obtain a string from the keyboard you can use the next method of Scanner
day = sc.next();
String methods ……
charAt
Accepts an integer and returns the character at that position in the string. Note that indexing starts from zero, not 1!
An item of type
int
An item of type
char
length Returns the length of the string .
None An item of type
int
substring Accepts two integers (eg m and n) and returns a copy of a chunk of the string, from position m to position n-1.
Two items of type
int
A String
object
concat Accepts a string and returns a new string consisting of the that string joined to the end of the original string.
A String
object
A String
object
Method Description Inputs Output
toUpperCase
Returns a copy of the original string, all upper case.
None A String object
toLowerCase Returns a copy of the original string, all lower case.
None A String object
compareTo
Accepts a string and compares it to the object's string. It returns zero if the strings are identical, a negative number if the object's string comes first in the alphabet, and a positive number if it comes later.
A String object
An item of type
int.
equals Accepts an object and compares this to this to the string. It returns true if these are identical, otherwise returns false.
An object of any class
A boolean
value.
Method Description Inputs Output
import java.util.*;
public class StringTest
{
public static void main(String[ ] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
System.out.print("Enter a string: ");
str = sc.next();
System.out.println("The length of the string is " + str.length());
System.out.println("The character at position 3 is " + str.charAt(2));
System.out.println("Characters 2 to 4 are " + str.substring(1,4));
System.out.println(str.concat(" was the string entered"));
System.out.println("This is upper case: " + str.toUpperCase());
System.out.println("This is lower case: " + str.toLowerCase());
}
}
;
Enter a string: Europe
The length of the string is 6
The character at position 3 is r
Characters 2 to 4 are uro
Europe was the string entered
This is upper case: EUROPE
This is lower case: europe
RUN
import java.util.*;
public class StringTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
System.out.print("Enter a string: ");
str = sc.next();
System.out.println("The length of the string is " + str.length());
System.out.println("The character at position 3 is " + str.charAt(2));
System.out.println("Characters 2 to 4 are " + str.substring(1,4));
System.out.println(str.concat(" was the string entered"));
System.out.println("This is upper case: " + str.toUpperCase());
System.out.println("This is lower case: " + str.toLowerCase());
}
}
Comparing strings …..
When checking two strings for equality use the equals method!
Do not use the equality operator (==)
if(firstString == secondString){ // more code here}
String firstString = “Hello”;
String secondString = “Goodbye”;
if(firstString == secondString){ // more code here}
String firstString = “Hello”;
String secondString = “Goodbye”;
if(firstString.equals(secondString)){ // more code here}
String firstString = “Hello”;
String secondString = “Goodbye”;
if(firstString.equals(secondString)){ // more code here}
String firstString = “Hello”;
String secondString = “Goodbye”;
When comparing two strings alphabetically use the compareTo method!
import java.util.*;
public class StringComp
{
public static void main(String[ ] args)
{
Scanner sc = new Scanner(System.in);
String string1, string2;
int comparison;
System.out.print("Enter a String: ");
string1 = sc.next();
System.out.print("Enter another String: ");
string2 = sc.next();
comparison = string1.compareTo(string2);
// check comparison
}
}
if (comparison < 0)
{
System.out.println(string1 + " comes before " + string2
+ " in the alphabet");
}
else if (comparison > 0)
{
System.out.println(string2 + " comes before " + string1
+ " in the alphabet");
}
else
{
System.out.println("The strings are identical");
}
RUN
Enter a String:
Enter another String:
goodbye comes before hello in the alphabet
hello
goodbye
Using some classes written for you
Using some classes written for you
Oblong
Using some classes written for you
Oblong
EasyScanner
Using some classes written for you
Oblong
EasyScanner
BankAccount
Oblong
public class RectangleCalculations{ public static void main(String[ ] args) {
double length, height;// code to get length and heightSystem.out.println(“Area = " + area(length,height) ); System.out.println(“Perimeter = " +
perimeter(length,height) );
private static double area (double lengthIn, double heightIn) {
return lengthIn * heightIn; }
private static double area (double lengthIn, double heightIn) {
return 2* (lengthIn * heightIn_; }}
public class RectangleCalculations{ public static void main(String[ ] args) {
double length, height;// code to get length and heightSystem.out.println(“Area = " + area(length,height) ); System.out.println(“Perimeter = " +
perimeter(length,height) ); }
private static double area (double lengthIn, double heightIn) {
return lengthIn * heightIn; }
private static double area (double lengthIn, double heightIn) {
return 2* (lengthIn + heightIn); }}
Methods of the Oblong class..
Oblong
Oblong myOblong
12.5
20
= new Oblong(12.5, 20);
setLength
myOblong.setlength(17.5);
12.5
20
17.5
setHeight
myOblong.setHeight(12);
20
17.5
12
getHeight
System.out.println( );
17.5
12
myOblong.getHeight( )
getLength
System.out.println( );
17.5
12
myOblong.getLength( )
calculateArea
System.out.println( );
17.5
12
myOblong.calculateArea( )
calculatePerimeter
System.out.println( );
17.5
12
myOblong.calculatePerimeter( )
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 double types;
• the next method doesn't allow us to enter strings containing spaces.
The EasyScanner class resolves these problems!
The input methods of the EasyScanner class
Java type EasyScanner method
int nextInt()
double nextDouble()
char nextChar()
String nextString()
To use the methods of EasyScanner we do not need to create an object!
char c;
System.out.print("Enter a character: ");
c = EasyScanner.nextChar();
String s;
System.out.print("Enter a string: ");
s = EasyScanner.nextString();
The BankAccount class ….
The BankAcount class contains methods to process a bank account.
BankAccount
99786754Susan Richards
500.0
46376205 Sumana Khan
150.0
The methods of the BankAccount classMethod Description Inputs Output
BankAccount A constructor. It accepts two strings and assigns them to the account number and account name respectively. It also sets the account balance to zero.
Two String objects
Not applicable
getAccountNumber Returns the account number. None An item of type String
getAccountName Returns the account name. None An item of type String
getBalance Returns the balance. None An item of type double
deposit Accepts an item of type double and adds it to the balance
An item of type double
None
withdraw Accepts an item of type double and subtracts it from the balance
An item of type double
None
public class BankAccountTester
{
public static void main(String[ ] args)
{
BankAccount account1
= new BankAccount("99786754","Susan Richards");
account1.deposit(1000);
System.out.println("Account number: "
+ account1.getAccountNumber());
System.out.println("Account name: " +
account1.getAccountName());
System.out.println("Current balance: " + account1.getBalance());
}
}
Account number: 99786754
Account name: Susan Richards
Current balance: 1000.0
Arrays of objects ..
int[] someArray = new int[3];
An array of 3 integers
An array of 3 BankAccount objects
BankAccount[] accountList= new BankAccount[3];
The effect on memory of creating an array of objects …
null
null
null
accountList
accountList
= new BankAccount [3];
reference to bank account
reference to bank account
reference to bank account
Java instructionComputer memory
BankAccount[] accountList;
null
Adding bank accounts to the array …
accountList[0] = new BankAccount("99786754","Susan Richards");
accountList[1] = new BankAccount("44567109","Delroy Jacobs");
accountList[2] = new BankAccount("46376205","Sumana Khan");
accountList[1]
BankAccountwith account number
"46376205" and name "Sumana Khan"
accountList[2]
accountList[0]
BankAccount with account number "99786754" and name
"Susan Richards"
BankAccount with account number "44567109" and name
"Delroy Jacobs"
accountList
Accessing objects in an array ….
accountList[0].deposit(1000);
returns a BankAccount object
calls a BankAccount method
accountList[0].withdraw(500);
accountList[2].deposit(150);
public class BankAccountTester2
{
public static void main(String[ ] args)
{
BankAccount[ ] accountList = new BankAccount[3];
accountList[0] = new BankAccount("99786754","Susan Richards");
accountList[1] = new BankAccount("44567109","Delroy Jacobs");
accountList[2] = new BankAccount("46376205","Sumana Khan");
accountList[0].deposit(1000);
accountList[2].deposit(150);
accountList[0].withdraw(500);
for(BankAccount item : accountList)
{
System.out.println("Account number: " + item.getAccountNumber());
System.out.println("Account name: " + item.getAccountName());
System.out.println("Current balance: " + item.getBalance());
System.out.println();
}
}
}
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
Practical Work
Follow these steps to make use of classes written for you (such as Oblong and EasyScanner)..
First, go to this module’s web site and download the classes we have written for you..
Now, every time your program needs to use a file (such as Oblong), add it to your project!
This program needs access to the Oblong class
Right click your project (or choose Project from the menu)
Choose Add >Add Exisiting Files
Select the file(s) you need.
You will be asked if you want this file to be added into your project or kept outside.
Select Add to add the file into your project.
File has been added and your program will now compile!
Remember the programs you write should not have the same name as our files!
public class TestOblong
{
public static void main (String[ ] args)
{
Oblong ob1 = new Oblong (4.2, 10);
System.out.println("area = " + ob1.calculateArea());
System.out.println("permeter = " + ob1.calculatePerimeter());
}
}
public class TestOblong
{
public static void main (String[ ] args)
{
Oblong ob1 = new Oblong (4.2, 10);
System.out.println("area = " + ob1.calculateArea());
System.out.println("permeter = " + ob1.calculatePerimeter());
}
}
public class TestOblong
{
public static void main (String[ ] args)
{
Oblong ob1 = new Oblong (4.2, 10);
System.out.println("area = " + ob1.calculateArea());
System.out.println("permeter = " + ob1.calculatePerimeter());
}
}
public class TestOblong
{
public static void main (String[ ] args)
{
Oblong ob1 = new Oblong (4.2, 10);
System.out.println("area = " + ob1.calculateArea());
System.out.println("permeter = " + ob1.calculatePerimeter());
}
}
area = 42.0
area = 42.0
public class TestOblong
{
public static void main (String[ ] args)
{
Oblong ob1 = new Oblong (4.2, 10);
System.out.println("area = " + ob1.calculateArea());
System.out.println("perimeter = " + ob1.calculatePerimiter());
}
}
public class TestOblong
{
public static void main (String[ ] args)
{
Oblong ob1 = new Oblong (4.2, 10);
System.out.println("area = " + ob1.calculateArea());
System.out.println("perimeter = " + ob1.calculatePerimiter());
}
}
area = 42.0
perimeter = 28.4
Design and implement a program that performs in the following way:
• when the program starts two bank accounts are created, using names and numbers which are written into the code;
• the user is then asked to enter an account number, followed by an amount to deposit in that account;
• the balance of the appropriate account is then updated accordingly – or if an incorrect account number was entered a message to this effect is displayed;
• the user is then asked if he or she wishes to make more deposits;
• if the user answers 'y' (for yes), the process continues;
• if the user answers 'n' (for no), then both account details (account number, account name and balance) are displayed.
***Bank Program***
Which bank account?:
***Bank Program***
Which bank account?: a123
***Bank Program***
Which bank account?: a123
How much to deposit?
***Bank Program***
Which bank account?: a123
How much to deposit? 250
***Bank Program***
Which bank account?: a123
How much to deposit? 250
More deposits?
***Bank Program***
Which bank account?: a123
How much to deposit? 250
More deposits? n
***Bank Program***
Which bank account?: a123
How much to deposit? 250
More deposits? n
number: a123 name: Aaron balance: 250.0
number: a456 name: Obama balance: 0.0