Unit 3 - Objects and Classes
Unit 3 - Objects and Classes
Unit 3 Goals
2
Defining Classes for Objects
3
Classes
• Classes are constructs that define objects of the same
type.
Access modifier Class Name
Class Members
public double getArea() {
Instance //getArea() method implementation
method } //end of method body
Data Fields:
radius is _______
Methods:
getArea
5
Java Classes
public class Circle {
/** The radius of this circle */
private double radius; Data field
private:
public:
8
Why data fields should be private?
• To protect data (encapsulation)
• To make class easier to maintain
How to retrieve and modify a data field?
• Use get (accessor) method to return its value (to make a private data field
accessible)
• Use set (mutator) method to set a new value (to modify private properties)
Circle
The - sign indicates
private modifier -radius: double The radius of this circle
Data field
encapsulation +Circle() Constructs a default circle object.
is to prevent direct +Circle(radius: double)
modifications of Constructs a circle object with the specified radius.
data fields. +getRadius(): double Returns the radius of this circle (accessor).
+setRadius(radius: double): void Sets a new radius for this circle (mutator).
+getArea(): double Returns the area of this circle.
9
Accessor & Mutator methods
• Accessor methods – methods to read private properties.
• Mutator methods – methods to modify private properties.
// Accessor
public double getRadius() {
return radius;
}
// Mutator
public void setRadius(int r) {
if(r > 0) // guards illegal value
radius = r;
}
// ...
}
10
Accessing Object’s Members
11
Accessing Object’s Members
Dot operator or
Object member
access operator
// Create a circle with default radius
Circle c1 = new Circle();
c1.setRadius(10); // mutator method
System.out.println("Circle 1 area is : " + c1.getArea());
13
Constructors
• Constructors are a special kind of methods that are invoked to
construct objects.
• Constructors must have the same name as the class itself.
• Constructors do not have a return type—not even void.
• A constructor with no parameters is referred to as a no-arg constructor.
• Constructors play the role of initializing objects.
15
Difference between constructor and method in Java
Constructors Methods
A method is a collection of
A constructor is used to construct
statements grouped together to
and initialize objects from a class.
perform an operation
The constructor name must be The method name may or may not
same as the class name. be same as the class name.
Default Constructor
• A class may be defined without constructors. In this case,
a no-arg constructor with an empty body is implicitly
declared in the class.
• This constructor, called a default constructor, is provided
automatically only if no constructors are explicitly defined
in the class.
public class Circle {
private double radius;
Example: Create
Assign object
reference an object
Stack Heap
A Circle object
The myCircle
variable holds the
address of the Circle myCircle reference radius: 5.0
object.
22
Data Values
23
Default Value for a Data Field
24
No Default Value for a Local Variable
25
this Reference Keyword
26
this Reference
public Student()
{
stuNum = 100; // implicit
this.stuNum = 100; // explicit
}
}
27
this Reference
public class Student
{
private int stuNum;
Identical to the class field names
public Student(int stuNum)
{
stuNum = stuNum;
}
Output:
Student# : 101
29
this Reference
public Student()
{
this(100); // invoke Student(100);
}
}
30
Differences Between Variables
31
Differences between Variables of
Primitive Data Types and Object (Reference) Types
i 1 i 2
j 2 j 2
c1 c1
c2 c2
Garbage
33
Garbage Collection
34
Passing Object References to Method
35
Passing Object References to a Method
• A class type variable does not hold the actual data item that
is associated with it, but holds the memory address of the
object.
36
Passing Object References to a Method
• Example:
38
Passing Objects
class PassObject {
public static void main(String[] args){
Student object
Student stu= new Student();
created
increaseCGPA(stu);
40
Visibility Modifiers
41
Visibility Modifiers
42
Visibility Modifiers
43
Immutable
44
Immutable Objects and Classes
• If you delete the set method in the Circle class below, the class would
be immutable because radius is private and cannot be changed
without a set method.
Circle
-radius: double
+Circle()
+Circle(radius: double)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
45
Immutable Objects and Classes
• If a class contains only private data fields and no set methods, is the
class immutable?
• Not necessary!
public class Person {
private int id;
private BirthDate birthDate;
48
Immutable Objects and Classes
49
Strings are Immutable Objects
str1 “testing”
return
str2 “TESTING”
50
PassString.java
public class PassString
{
public static void main(String[] args)
{
// Create a String object containing "Shakespeare".
String name = "Shakespeare";
51
Variables and Methods
52
Instance Variables and Methods
53
Static Variables, Methods
54
Static Variables, Methods
public class Emp
{
int empNum; // instance variable
Emp() {
empNum = 999;
numberOfObjects++; Emp
}
empNum: int
Emp(int num) { numberOfObjects: int
empNum = num;
numberOfObjects++; +getNumberOfObjects(): int
} +getEmpNum(): int
55
Static Variables, Methods
public class TestEmp
{
public static void main(String[] args)
{
Emp clerk = new Emp();
System.out.println("Clerk ID is " + clerk.empNum + " and of Emp object is " + clerk.numberOfObjects);
instantiate Memory
clerk
UML Notation:
+: public variables or methods
underline: static variables or methods
56
Static Variables, and Methods
public class TestEmp
{
public static void main(String[] args)
{
Emp clerk = new Emp();
System.out.println("Clerk ID is " + clerk.empNum + " and of Emp object is " + clerk.numberOfObjects);
instantiate Memory
clerk
58
Instance method vs. Static method
Class (static) Class (static) Instance (non- Instance (non-
variable method static) variable static) method
Class (static)
method
Instance (non-
static) method
class MyClass {
private int instanceVar;
private static int staticVar;
public void instanceMethod() {
instanceVar++; // OK
instanceMethod2(); // OK
staticVar++; // OK
staticMethod2(); // OK
}
public static void staticMethod() {
instanceVar++; // Error
instanceMethod(); // Error
staticVar++; // OK
staticMethod2(); // OK
}
public void instanceMethod2() {}
public static void staticMethod2() {};
} 59
When to make a method static
60
Java Package
61
Java Package
• Packages are nothing more than the way we organize files into different
directories according to their functionality, usability, as well as category
they should belong to.
package world;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
62
Java Package
• Next, put the source file in a directory whose name reflects the name of
the package, for our example:
(..\src\)world\HellowWorld.java
• Like the .java source files, the compiled .class files should be in a series
of directories that reflect the package name:
(..\bin\)world\HellowWorld.class
import world.HellowWorld;
63
Creating package with Eclipse
64
Creating package with Eclipse
67
Using Classes from the Java Library
https://docs.oracle.com/javase/8/docs/api/
68
The Random Class
• You have used Math.random() to obtain a random double
value between 0.0 and 1.0 (excluding 1.0).
(0 <= Math.random() < 1.0)
• A more useful random number generator is provided in the
java.util.Random class.
java.util.Random
+Random() Constructs a Random object with the current time as its seed.
+Random(seed: long) Constructs a Random object with a specified seed.
+nextInt(): int Returns a random int value.
+nextInt(n: int): int Returns a random int value between 0 and n (exclusive).
+nextLong(): long Returns a random long value.
+nextDouble(): double Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean Returns a random boolean value.
69
The Random Class Example
• If two Random objects have the same seed, they will generate
identical sequences of numbers. For example, the following
code creates two Random objects with the same seed 3.
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
70
The String Class
• In Java, String is a class, you can create object of this class:
String greeting = new String("Greeting");
71
Interned String Instance
• Since strings are immutable and are frequently used, to
improve efficiency and save memory, the JVM uses a unique
instance for string literals called interned string.
72
String Comparison
java.lang.String
+equals(s1: String): boolean Returns true if this string is equal to string s1.
+equalsIgnoreCase(s1: String): Returns true if this string is equal to string s1 case-
boolean insensitive.
+compareTo(s1: String): int Returns an integer greater than 0, equal to 0, or less than 0
to indicate whether this string is greater than, equal to, or
less than s1.
+compareToIgnoreCase(s1: String): Same as compareTo except that the comparison is case-
int insensitive.
+regionMatches(toffset: int, s1: String, Returns true if the specified subregion of this string exactly
offset: int, len: int): boolean matches the specified subregion in string s1.
+regionMatches(ignoreCase: boolean, Same as the preceding method except that you can specify
toffset: int, s1: String, offset: int, whether the match is case-sensitive.
len: int): boolean
+startsWith(prefix: String): boolean Returns true if this string starts with the specified prefix.
+endsWith(suffix: String): boolean Returns true if this string ends with the specified suffix.
73
String Comparisons
String s1 = new String("Welcome");
String s2 = "Welcome";
String s3 = "Welcome";
s3 = "Weldom";
System.out.println("Welcome > Weldom : " + s2.compareTo(s3) ); // -1
s3 = "Malaysia";
// true
System.out.println("Malaysia start with Mal : " + s3.startsWith("Mal"));
// false
System.out.println("Malaysia start with z : " + s3.startsWith("z"));
// true
System.out.println("lay is in Malaysia : " + "lay".regionMatches(0, s3,
2, 3));}
74
String Length, Characters, and Combining Strings
java.lang.String
+length(): int Returns the number of characters in this string.
+charAt(index: int): char Returns the character at the specified index from this string.
+concat(s1: String): String Returns a new string that concatenate this string with string s1.
string.
75
Extracting Substrings
java.lang.String
+subString(beginIndex: int): Returns this string’s substring that begins with the character at the
String specified beginIndex and extends to the end of the string.
+subString(beginIndex: int, Returns this string’s substring that begins at the specified
endIndex: int): String beginIndex and extends to the character at index endIndex – 1.
Note that the character at endIndex is not part of the substring.
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message W e l c o m e t o J a v a
java.lang.String
+toLowerCase(): String Returns a new string with all characters converted to lowercase.
+toUpperCase(): String Returns a new string with all characters converted to uppercase.
+trim(): String Returns a new string with blank characters trimmed on both sides.
+replace(oldChar: char, Returns a new string that replaces all matching character in this
newChar: char): String string with the new character.
+replaceFirst(oldString: String, Returns a new string that replaces the first matching substring in
newString: String): String this string with the new substring.
+replaceAll(oldString: String, Returns a new string that replace all matching substrings in this
newString: String): String string with the new substring.
+split(delimiter: String): Returns an array of strings consisting of the substrings split by the
String[] delimiter.
77
Converting, Replacing, and Splitting Strings
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string, WELCOME.
" Welcome ".trim() returns a new string, Welcome.
"Welcome".replace('e', 'A') returns a new string, WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string, WABlcome.
"Welcome".replace("e", "AB") returns a new string, WABlcomAB.
"Welcome".replace("el", "AB") returns a new string, WABcome.
78
Splitting a String
output:
Java HTML Perl
79
Finding a Character or a Substring in a String
java.lang.String
+indexOf(ch: char): int Returns the index of the first occurrence of ch in the string.
Returns -1 if not matched.
+indexOf(ch: char, fromIndex: Returns the index of the first occurrence of ch after fromIndex in
int): int the string. Returns -1 if not matched.
+indexOf(s: String): int Returns the index of the first occurrence of string s in this string.
Returns -1 if not matched.
+indexOf(s: String, fromIndex: Returns the index of the first occurrence of string s in this string
int): int after fromIndex. Returns -1 if not matched.
+lastIndexOf(ch:char): int Returns the index of the last occurrence of ch in the string.
Returns -1 if not matched.
+lastIndexOf(ch:char, Returns the index of the last occurrence of ch before fromIndex
fromIndex: int): int in this string. Returns -1 if not matched.
+lastIndexOf(s: String): int Returns the index of the last occurrence of string s. Returns -1 if
not matched.
+lastIndexOf(s: String, Returns the index of the last occurrence of string s before
fromIndex: int): int fromIndex. Returns -1 if not matched.
80
Finding a Character or a Substring in a String
81
The StringBuilder Class
• The StringBuilder class is an alternative to the String class.
java.lang.StringBuilder
82
StringBuilder Examples
StringBuilder sb = new StringBuilder("Welcome to ");
Output:
Welcome to Java
Welcome to HTML and Java
Welcome to Java
Welcome to HTML
LMTH ot emocleW
83
The Character Class
• The Character class has several static methods for determining a
character’s category (uppercase, lowercase, digit, and so on) and for
converting characters from uppercase to lowercase, and vice versa,.
java.lang.Character
85