Classes and objects Learning objectives By the end of this lecture you should be able to: • 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.
39
Embed
Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Classes and objects
Learning objectives
By the end of this lecture you should be able to:
• 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.
Dealing with complexity
Structured programming
boolean light;
String roomNumber
int mark;
// switch on light
// get building
// check if passed
main
Object-oriented programming
boolean light;
String roomNumber
int mark;
// switch on light
// get building
// check if passed
RoomStudentProjector
Classes
A class is the blueprint from which objects are generated;
Student
data
methods
Class
Objects
Student s1;
Student s2;
Student s3;
Student s4;
A class can also be thought of as a type!
?
When we use a class as a data type, we need information about its methods only.
Creating Objects
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);
A constructor is a special method that generates an object from a class.
Effect on computer memory
Robot r1 ;
Computer Memory Java Instructions
r1
This is the space for the new Robot
object
r1 = new Robot( 5, 50);
null
Pre-defined Java classes
We have already been using a few pre-defined classes in our programs:
Scanner
String
Revisiting the Scanner and String classes
To create a Scanner object we call the Scanner constructor:
Scanner sc = new Scanner (System.in);
The String class is different from all other classes in Java.
We can create String objects without a call to a constructor:
String s = “Wednesday”; new String (“Wednesday”);
Revisiting the Scanner and String classes
We also used methods of the Scanner and String classes.
int x = sc.nextInt();
String s = sc.next();
char reply = sc.next().charAt(0);
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 comparing two objects, such as Strings, we should
do so by using a method called equals;
We should not use the equality operator (==);
if(firstString == secondString)
{
// more code here
}
String firstString = “Hello”;
String secondString = “Goodbye”;
if(firstString.equals(secondString))
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
We have written some classes for you to use:
Oblong
EasyScanner
BankAccount
Next week we will show you how we wrote them.
Methods of the Oblong class
The constructor.
Takes two items of data, both of type double, representing the length and height of the oblong respectively.
Oblong
Oblong myOblong
12.5
20
= new Oblong(12.5, 20);
Methods of the Oblong class
Takes an item type double and re-sets the length of the oblong.
Returns no value.
setLength
myOblong.setlength(17.5);
12.5
20
17.5
Methods of the Oblong class
Takes an item type double and re-sets the height of the oblong.
Returns no value.
setHeight
myOblong.setHeight(12);
20
17.5
12
Methods of the Oblong class
Takes no parameters and returns the value of the height of the oblong
getHeight
System.out.println( );
17.5
12
myOblong.getHeight( )
Methods of the Oblong class
Takes no parameters and returns the value of the length of the oblong.
getLength
System.out.println( );
17.5
12
myOblong.getLength( )
Methods of the Oblong class
Takes no parameters and returns the area of the oblong.
calculateArea
System.out.println( );
17.5
12
myOblong.calculateArea( )
Methods of the Oblong class
Takes no parameters and returns the perimiter of the oblong.
calculatePerimeter
System.out.println( );
17.5
12
myOblong.calculatePerimeter( )
The EasyScanner class
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 input methods of the EasyScanner class
Java type EasyScanner method
int nextInt()
double nextDouble()
char nextChar()
String nextString()
Examples of using EasyScanner
char c;
System.out.print("Enter a character: ");
c = EasyScanner.nextChar();
String s;
System.out.print("Enter a string: ");
c = EasyScanner.nextString();
The BankAccount class
Contains methods to process bank accounts.
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