Understanding Time Class in Java
Understanding Time Class in Java
2
Classes and Objects:
A Deeper Look
© .
2
OBJECTIVES
In this chapter you will learn:
▪ Encapsulation and data hiding.
▪ Data abstraction and abstract data types (ADTs).
▪ To use keyword this.
▪ To use static variables and methods.
▪ To use static import.
▪ To use the enum type to create set of constants with
unique identifiers.
▪ How to declare enum constants with parameters.
© .
3
© .
4
© .
5
© .
6
© .
7
© .
8
© .
1 // Fig. 8.2: [Link] 9
2 // Time1 object used in an application.
3
4 public class Time1Test
5 { Create a Time1 object
[Link]
6 public static void main( String args[] )
7 {
8 // create and initialize a Time1 object
9 Time1 time = new Time1(); // invokes Time1 constructor (1 of 2)
10
11 // output string representations of the time
12 [Link]( "The initial universal time is: " );
13 [Link]( [Link]() );
14 [Link]( "The initial standard time is: " );
15 [Link]( [Link]() );
16 [Link](); // output a blank line
17
Call toUniversalString method
© .
18 // change time and output updated time 10
19 [Link]( 13, 27, 6 ); Call setTime method
20 [Link]( "Universal time after setTime is: " );
21 [Link]( [Link]() );
22 [Link]( "Standard time after setTime is: " );
[Link]
23 [Link]( [Link]() );
24 [Link](); // output a blank line
25 (2 of 2)
26 // set time with invalid values; output updated time
27 [Link]( 99, 99, 99 );
28 [Link]( "After attempting invalid settings:" );
29 [Link]( "Universal time: " );
30 [Link]( [Link]() ); Call setTime method
31 [Link]( "Standard time: " ); with invalid values
32 [Link]( [Link]() );
33 } // end main
34 } // end class Time1Test
mappings
hour
0 1 41 19 13 3
mapped to
12 01 41 7 13 03
AM PM
© .
12
mappings
( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
if hour is 0 or 12
12 is returned
else
hour mode 12 is returned
Examples:
Time:00:15:20 -> 12:15:20 AM
Time:05:15:20 -> 5:15:20 AM
Time:12:15:20 -> 12:15:20 PM
Time:21:15:20 -> 9:15:20 PM
© .
13
© .
14
© .
15
Constructors of Time
5 constructors
Time() // no argument constructor
© .
16
© .
52 // validate and set hour 19
53
54
Outline
public void setHour( int h )
{
55 hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
56 } // end method setHour
57
[Link]
58 // validate and set minute
59 public void setMinute( int m )
60 { (3 of 4)
61 minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
62 } // end method setMinute
63
64 // validate and set second
65 public void setSecond( int s )
66 {
67 second = ( ( s >= 0 && s < 60 ) ? s : 0 );
68 } // end method setSecond
69
70 // Get Methods
71 // get hour value
72 public int getHour()
73 {
74 return hour;
75 } // end method getHour
76
© .
77 // get minute value 20
78
79
Outline
public int getMinute()
{
80 return minute;
81 } // end method getMinute
82 [Link]
83 // get second value
84 public int getSecond()
85 {
86 return second; (4 of 4)
87 } // end method getSecond
88
89 // convert to String in universal-time format (HH:MM:SS)
90 public String toUniversalString()
91 {
92 return [Link](
93 "%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
94 } // end method toUniversalString
95
96 // convert to String in standard-time format (H:MM:SS AM or PM)
97 public String toString()
98 {
99 return [Link]( "%d:%02d:%02d %s",
100 ( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
101 getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
102 } // end method toString
103 } // end class Time2
© .
21
© .
22
© .
23
20 [Link](
21 "t2: hour specified; minute and second defaulted" );
22 [Link]( " %s\n", [Link]() );
23 [Link]( " %s\n", [Link]() );
Time2Test.
24 java
25 [Link](
26 "t3: hour and minute specified; second defaulted" );
27 [Link]( " %s\n", [Link]() ); (2 of 3)
28 [Link]( " %s\n", [Link]() );
29
30 [Link]( "t4: hour, minute and second specified" );
31 [Link]( " %s\n", [Link]() );
32 [Link]( " %s\n", [Link]() );
33
34 [Link]( "t5: all invalid values specified" );
35 [Link]( " %s\n", [Link]() );
36 [Link]( " %s\n", [Link]() );
37
© .
24
© .
25
© .
26
NOTE: Module feature introduced in Java 9 as Java Platform Module System (JPMS)
• Modules are a higher level of code organization compared to packages.
• Allow to explicitly define which packages are visible to other modules
(using the exports keyword) and which modules are required by current module
(using the requires keyword).
© .
27
© .
28
MemberAccessTest
1 // Fig. 8.3: [Link] .java
2 // Private members of class Time1 are not accessible.
3 public class MemberAccessTest
4 {
5 public static void main( String args[] )
6 {
7 Time1 time = new Time1(); // create and initialize Time1 object
8
9 [Link] = 7; // error: hour has private access in Time1
10 [Link] = 15; // error: minute has private access in Time1
11 [Link] = 30; // error: second has private access in Time1
12 } // end main
Attempting to access private instance variables
13 } // end class MemberAccessTest
© .
1 // Fig. 8.4: [Link] 30
2 // this used implicitly and explicitly to refer to members of an object.
3
4 public class ThisTest
5 { Create new SimpleTime object
6 public static void main( String args[] )
[Link]
7 {
8 SimpleTime time = new SimpleTime( 15, 30, 19 );
(1 of 2)
9 [Link]( [Link]() );
10 } // end main A java file can contain more than one class,
11 } // end class ThisTest but only one class in each .java file can be
12 public
13 // class SimpleTime demonstrates the "this" reference
14 class SimpleTime
15 {
16 private int hour; // 0-23
Declare instance variables
17 private int minute; // 0-59
18 private int second; // 0-59
19
20 // if the constructor uses parameter names identical to
21 // instance variable names the "this" reference is
22 // required to distinguish between names
23 public SimpleTime( int hour, int minute, int second ) Method parameters shadow
24 {
instance variables
25 [Link] = hour; // set "this" object's hour
26 [Link] = minute; // set "this" object's minute
27 [Link] = second; // set "this" object's second
28 } // end SimpleTime constructor
29
© .
30 // use explicit and implicit "this" to call toUniversalString 31
31 public String buildString()
32 { [Link]
33 return [Link]( "%24s: %s\n%24s: %s",
34 "[Link]()", [Link](),
(2 of 2)
35 "toUniversalString()", toUniversalString() );
36 } // end method buildString Using this explicitly or implicitly
37 to call toUniversalString
38 // convert to String in universal-time format (HH:MM:SS)
39 public String toUniversalString()
40 {
41 // "this" is not required here to access instance variables,
42 // because method does not have local variables with same
43 // names as instance variables
44 return [Link]( "%02d:%02d:%02d",
45 [Link], [Link], [Link] );
46 } // end method toUniversalString
Use of this not necessary here
47 } // end class SimpleTime
[Link](): 15:30:19
toUniversalString(): 15:30:19
© .
32
© .
33
© .
34
© .
35
public class Person {
private String name;
© .
37
© .
38
// Parameterized constructor
public MyClass(int value) {
[Link] = value;
}
// Getter method
public int getValue() {
return value;
}
© .
39
© .
40
© .
41
public class MyClass {
private String name;
public MyClass(String name) { // constructor
[Link] = name;
}
// This is an instance method with the same name as the class
public void MyClass() { // method
[Link]("This is a method with the same name as the class.");
}
public void printName() {
[Link]("Name: " + name);
}
public static void main(String[] args) {
MyClass myObject = new MyClass("John");
[Link](); OUTPUT :
Name: John
[Link]();
This is a method with the same name as the class.
}
} © .
42
2.6 Composition
▪ OOP allows to create complex objects by combining or
"composing" simpler objects.
© .
43
© .
1 // Fig. 8.7: [Link] 44
© .
22 // utility method to confirm proper month value 45
© .
46
41 // check if day in range for month
42 if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
43 return testDay;
[Link]
44
45 // check for leap year (3 of 3)
46 if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
47 ( year % 4 == 0 && year % 100 != 0 ) ) )
Check if the day is
48 return testDay; February 29 on a
49 leap year
50 [Link]( "Invalid day (%d) set to 1.", testDay );
51 return 1; // maintain object in consistent state
52 } // end method checkDay
53
54 // return a String of the form month/day/year
55 public String toString()
56 {
57 return [Link]( "%d/%d/%d", month, day, year );
58 } // end method toString
59 } // end class Date
© .
47
© .
1 // Fig. 8.8: [Link] 48
2 // Employee class with references to other objects.
3
4 public class Employee
5 {
[Link]
6 private String firstName;
Employee contains references
7 private String lastName;
to two Date objects
8 private Date birthDate;
9 private Date hireDate;
10
11 // constructor to initialize name, birth date and hire date
12 public Employee( String first, String last, Date dateOfBirth,
13 Date dateOfHire )
14 {
15 firstName = first;
16 lastName = last;
17 birthDate = dateOfBirth;
18 hireDate = dateOfHire;
19 } // end Employee constructor
20 Implicit calls to hireDate and
21 // convert Employee to String format birthDate’s toString methods
22 public String toString()
23 {
24 return [Link]( "%s, %s Hired: %s Birthday: %s",
25 lastName, firstName, hireDate, birthDate );
26 } // end method toString
27 } // end class Employee
© .
1 // Fig. 8.9: [Link] 49
2 // Composition demonstration.
3
4 public class EmployeeTest
EmployeeTest
5 {
.java
6 public static void main( String args[] )
7 { Create an Employee object
8 Date birth = new Date( 7, 24, 1949 );
9 Date hire = new Date( 3, 12, 1988 );
10 Employee employee = new Employee( "Bob", "Blue", birth, hire );
11
12 [Link]( employee ); Display the Employee object
13 } // end main
14 } // end class EmployeeTest
© .
50
•finalize() method
– all classes in Java have finalize() method
• inherited from the Object class ([Link])
– it takes no parameters and has return type void
© .
51
© .
52
public class FinalizeExample {
public FinalizeExample() {
[Link]("Object created");
}
© .
53
•static fields
– also known as class variables
– used when:
• all objects of the class should share the same copy of the
instance variable or
• the instance variable (or method) should be accessible even
there is no object created from the class
static / non-static
method usage
// [Link](2,3);
© .
55
Employee Example
• Develop an Employee class which has
– Two instance variables
• firstname, lastname
– One static variable to count the employees
• count : counter - number of employees
– One constructor
• taking firstname and lastname
• increment count by 1 when creating a new employee
– One finalize method
• decrement count by 1 when distructing an employee object
– One get method for first and last name
– One static get method for counter
© .
56
Class Employee
5 public class Employee
6 { declare a static field
7 private String firstName;
8 private String lastName;
9 private static int count = 0; // number of objects in memory
© .
57
© .
58
Class EmployeeTest
Call static method getCount using class name Employee
4 public class EmployeeTest
5 {
6 public static void main( String args[] )
7 {
8 // show that count is 0 before creating Employees
9 [Link]( "Employees before instantiation: %d\n",
10 [Link]() );
Create new Employee objects
12 // create two Employees; count should be 2
13 Employee e1 = new Employee( "Susan", "Baker" );
14 Employee e2 = new Employee( "Bob", "Blue" );
16 // show that count is 2 after creating two Employees
17 [Link]( "\nEmployees after
Callinstantiation: " );
static method getCount
18 using%d\n",
[Link]( "via [Link](): variable name
[Link]() );
19 [Link]( "via [Link](): %d\n",
[Link]() );
20 [Link]( "via [Link](): %d\n",
21 [Link]() );
Call static method
getCount using class name
© .
61
31 e1 = null;
Remove references to objects, JVM will
32 e2 = null; mark them for garbage collection
34 [Link]();
// ask for garbage collection to occur now
© .
62
© .
63
© .
66
© .
67
© .
68
© .
69
13 } // end main
© .
70
© .
71
example
© .
72
© .
1 // Fig. 8.15: [Link] 73
2 // final instance variable in a class.
3
4 public class Increment
5 {
[Link]
6 private int total = 0; // total of all increments
7 private final int INCREMENT; // constant variable (uninitialized)
8
declare final
9 // constructor initializes final instance variable INCREMENT
instance variable
10 public Increment( int incrementValue )
11 {
12 INCREMENT = incrementValue; // initialize constant variable (once)
13 } // end Increment constructor
14 initialize final instance variable
15 // add INCREMENT to total inside a constructor
16 public void addIncrementToTotal()
17 {
18 total += INCREMENT;
19 } // end method addIncrementToTotal
20
21 // return String representation of an Increment object's data
22 public String toString()
23 {
24 return [Link]( "total = %d", total );
25 } // end method toIncrementString
26 } // end class Increment
© .
1 // Fig. 8.16: [Link] 74
2 // final variable initialized with a constructor argument.
3
4 public class IncrementTest
5 {
[Link]
6 public static void main( String args[] )
7 {
8 Increment value = new Increment( 5 ); create an Increment object
9
10 [Link]( "Before incrementing: %s\n\n", value );
11
12 for ( int i = 1; i <= 3; i++ ) call method addIncrementToTotal
13 {
14 [Link]();
15 [Link]( "After increment %d: %s\n", i, value );
16 } // end for
17 } // end main
18 } // end class IncrementTest
© .
75
© .
76
© .
77
// Output will be ➔ 5
© .
78
© .
79
© .
80
class TestExchange1
public class TestExchange1 {
public static void main(String[] args) {
int a = 2;
int b = 3;
[Link](“in main before exchange1:%8d
%8d\n”, a,b);
exchange1(a,b);
[Link](“in main after exchange1:%8d
%8d\n”,a,b);
© .
81
method exchange1
public static void exchange1(int x, int y) {
© .
82
class Int
Define a new type for integer
© .
83
class TestExchange2
public class TestExchange2 {
public static void main(String[] args) {
Int a = new Int(2);
Int b = new Int(3);
[Link](“in main before
excahnge2:%8d %8d\n”,[Link](),[Link]());
exchange2(a,b);
© .
84
method exchange2
public static void exchange2(Int x, Int y) {
[Link](“in method before exchange:
%8d %8d\n”,[Link](),[Link]());
int temp = [Link]();
[Link]([Link]());
[Link](temp);
[Link](“in method after exchange:
%8d %8d\n”, [Link](),[Link]());
© .
85
class TestExchange3
// Test class is the same as TestExchange2 class
// except send a and b to exchange3
public class TestExchange3 {
public static void main(String[] args) {
Int a = new Int(2);
Int b = new Int(3);
[Link](“in main before exchange3:
%8d %8d\n”, [Link](), [Link]());
exchange3(a,b);
method exchange3
public static void exchange3(Int x, Int y) {
[Link](“in method before exchange:
%8d %8d\n”, [Link](), [Link]());
© .
87
Explanations
• After executing
temp = x;
x = y;
y = temp;
© .
88
• Data abstraction
– Information hiding
• Classes normally hide the details of their implementation
from their clients
© .
89
• Data abstraction
– Abstract data types (ADTs)
• You can define your classes based on the behaviors of their
operations, without knowing implementation details.
© .
90
• Data abstraction
– Abstract Data Types (ADTs)
© .
91
class Point {
private double x;
private double y; • Lets develop a class: Point
public Point(double x, double y) { represents a 2D point in a
this.x = x; Cartesian Coordinate System
this.y = y;
} • It encapsulates the concept of
public double getX() { a point with x and y
return x;
coordinates (hides the internal
}
public double getY() { details of how a point is
return y; represented)
}
public void setX(double x) { • provides methods for accessing
this.x = x; and modifying the coordinates
} and calculating the distance
public void setY(double y) {
this.y = y; • It abstracts the concept of a
} point, allowing you to create
public double distanceTo(Point other) {
instances of points and perform
double dx = this.x - other.x;
double dy = this.y - other.y; operations on them without
return [Link](dx * dx + dy * dy); worrying about the underlying
} implementation.
}
© .
92
public class Main {
public static void main(String[] args) {
Point point1 = new Point(3.0, 4.0);
Point point2 = new Point(0.0, 0.0);
© .
93
• Queue ADT
– Similar to a “waiting line”
• Clients place items in the queue
– enqueue(item)
• Clients get items back from the queue
– dequeue(item)
• First-in, first out (FIFO) order
• Two pointers: front and rear (back)
© .
94
• Stack ADT
– There is a bucket that holds items
• Clients place items into the stack
– push(item)
• Clients get items back from the stack
– pop(item)
• Last-in, first-out (LIFO) order
• Only one pointer: top
• List ADT
• The items are not stored at
contiguous memory locations,
linked using pointers
• Clients add, search and remove items
– add
• add_head(item)
• add_pos(item)
• add_rear(item)
– remove(item)
– search(item)
• Generally two pointers: head and rear (tail)
© .
96
© .
98
package [Link];
Creating Packages
• Type-import-on-demand declaration
– imports all classes in a package
– example: import [Link].*;
© .
101
import java.*;
causes a compilation error.
© .
102
• Package access
– When a class, method or variable is declared without any
access modifier (e.g., class MyClass), it has package access.
© .
103
© .
104
public class PackageDataTest {
public static void main(String[] args) {
PackageData packageData = new PackageData();
© .
106
Enumerations
•enum types declared with an enum keyword
• comma-separated list of enum constants
• enum class has the following restrictions:
– enum types are implicitly final
– enum constants are implicitly static
– attempting to create an object of an enum type using new is a
compilation error
• enum constants can be used anywhere constants can
• enum constructor, like class constructors, can specify
parameters and can be overloaded
© .
107
Enumerations
© .
108
© .
109
© .
110
Enumerations: example
• Create a Java program (MonthEnum class) that defines
an enum type representing the months of the year.
© .
111
public class MonthEnum {
// Define an enum type to represent months of the year
enum Month {
[Link]
JANUARY("Jan", 31),
FEBRUARY("Feb", 28),
(1 of 3)
MARCH("Mar", 31),
APRIL("Apr", 30),
MAY("May", 31),
JUNE("Jun", 30),
JULY("Jul", 31),
AUGUST("Aug", 31),
SEPTEMBER("Sep", 30),
OCTOBER("Oct", 31),
NOVEMBER("Nov", 30),
DECEMBER("Dec", 31);
© .
113
// Iterating over enum values and accessing their abbreviations and days
[Link]("Months of the year:");
for (Month month : [Link]()) {
[Link](month + " (" + [Link]() + ") - " + [Link]()
+ " days");
} // end of for
} // end of main()
} // end of class
© .
114
Program Output :
Current month: NOVEMBER
Abbreviation: Nov
Number of days: 30
Months of the year:
JANUARY (Jan) - 31 days
FEBRUARY (Feb) - 28 days
MARCH (Mar) - 31 days
APRIL (Apr) - 30 days
MAY (May) - 31 days
JUNE (Jun) - 30 days
JULY (Jul) - 31 days
AUGUST (Aug) - 31 days
SEPTEMBER (Sep) - 30 days
OCTOBER (Oct) - 31 days
NOVEMBER (Nov) - 30 days
DECEMBER (Dec) - 31 days
© .
1 // Fig. 8.10: [Link] 115
2 // Declaring an enum type with constructor and explicit instance fields
3 // and accessors for these field
4 six enum decleration
5 public enum Book [Link]
6 {
7 // declare constants of enum type
8 JHTP6( "Java How to Program 6e", "2005" ),
(1 of 2)
9 CHTP4( "C How to Program 4e", "2004" ),
10 IW3HTP3( "Internet & World Wide Web How to Program 3e", "2004" ),
11 CPPHTP4( "C++ How to Program 4e", "2003" ),
12 VBHTP2( "Visual Basic .NET How to Program 2e", "2002" ),
13 CSHARPHTP( "C# How to Program", "2002" );
Arguments to be passed to
14
the enum constructor
15 // instance fields
16 private final String title; // book title
17 private final String copyrightYear; // copyright year
18
19 // enum constructor declaration of instance variables
20 Book( String bookTitle, String year )
21 {
22 title = bookTitle;
23 copyrightYear = year;
24 } // end enum Book constructor
25 declaration of enum constructor
© .
26 // accessor for field title 116
© .
1 // Fig. 8.11: [Link] 117
2
3
Outline
// Testing enum type Book.
import [Link];
4 [Link]
5 public class EnumTest
6 {
7 public static void main( String args[] ) (1 of 2)
8 {
9 [Link]( "All books:\n" );
10
dizideki her enum sabiti için döngü yinelemeleri
11 // print all books in enum Book
12 for ( Book book : [Link]() )
13 [Link]( "%-10s%-45s%s\n", book,
14 [Link](), [Link]() );
15
16 [Link]( "\nDisplay a range of enum constants:\n" );
17
18 // print first four books
19 for ( Book book : [Link]( Book.JHTP6, Book.CPPHTP4 ) )
20 [Link]( "%-10s%-45s%s\n", book,
21 [Link](), [Link]() );
22 } // end main
23 } // end class EnumTest
© .
118
All books:
© .
119
© .
120
?
public int getR() {
return r;
}
© .