0% found this document useful (0 votes)
16 views121 pages

Understanding Time Class in Java

This document provides an in-depth exploration of classes and objects in programming, focusing on encapsulation, data abstraction, and the use of constructors. It includes a case study of a Time class, detailing its methods, constructors, and how to manage time values effectively. The document also covers static members, enum types, and the importance of data hiding in object-oriented design.

Uploaded by

Nouredeen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views121 pages

Understanding Time Class in Java

This document provides an in-depth exploration of classes and objects in programming, focusing on encapsulation, data abstraction, and the use of constructors. It includes a case study of a Time class, detailing its methods, constructors, and how to manage time values effectively. The document also covers static members, enum types, and the importance of data hiding in object-oriented design.

Uploaded by

Nouredeen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

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

2.1 Case Study: Time Class


2.2 Time Class Overloaded Constructors
2.3 Controlling Access to Members
2.4 Referring to the Current Object’s
Members with this Reference
2.5 Default and No-Argument Constructors
2.6 Notes on set and get Methods
2.7 Composition
2.8 Garbage Collection and Method finalize

© .
4

2.9 static Class Members


2.10 static import
2.11 final Instance Variables
2.12 Sending simple types or references to methods
2.13 Data Abstraction and Encapsulation
2.14 Creating Packages: Time Class Case Study
2.15 Package Access

© .
5

2.1 Time Class Case Study:


(Methods of the Time1 class)
• Three instance variables of Time class
– declared as private
– primitive types (int)
– initilized to 0 when creating a Time1 object

• One method for changing time value


– public void setTime()

• Two methods for preparing String representation


of Time object in different formats
– public String toUniversalString()
– public String toString()

© .
6

Time Class Case Study


// Fig. 8.1: [Link]
// Time1 class declaration maintains the time in 24-hour format.
public class Time1 {
private int hour; // 0 – 23
private int minute; // 0 - 59
private int second; // 0 - 59

// set a new time value using universal time; ensure that


// the data remains consistent by setting invalid values to zero

public void setTime( int h, int m, int s ) {


// validate parameter values before setting instance variables
hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // validate hour
minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute
second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second
} // end method setTime

© .
7

Time Class Case Study (Cont.)


// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString() {
return [Link]( "%02d:%02d:%02d", hour, minute, second );
} // end method toUniversalString

// convert to String in standard-time format (H:MM:SS AM or PM)


public String toString() {
return [Link]( "%d:%02d:%02d %s",
( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
minute, second, ( hour < 12 ? "AM" : "PM" ) );
} // end method toString
} // end class Time1

© .
8

Test class for using Time1


Now, we write a test class for Time1

• create Time1 objects


default constructor
00:00:00

• set hour - munite - second values

• display in universal and standard formats

© .
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

Call toString 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

The initial universal time is: 00:00:00


The initial standard time is: 12:00:00 AM

Universal time after setTime is: 13:27:06


Standard time after setTime is: 1:27:06 PM

After attempting invalid settings:


Universal time: 00:00:00
Standard time: 12:00:00 AM
© .
11

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

2.2 Time Class Case Study:


Overloaded Constructors
• You can declare your own constructor to specify how
objects of a class should be initialized.
• Provide multiple constructor definitions of that class
to be initialized in different ways with different
signatures
• this reference can be used to invoke another
constructor
– allowed only as the first statement in a constructor’s body !

© .
14

class Time overview

• Rewrite Time class, it has


– 5 constructors
– 4 get and set methods
– 2 display methods

© .
15

Constructors of Time
5 constructors
Time() // no argument constructor

Time(int h) // specifies only hour,


minute and second values are 0

Time(int h, int m) // specifies hour and munite,


second value is 0

Time(int h, int m, int s) // specifies all values

Time(Time t) // takes a Time object and creates a


copy of the object extracting its
hour, minute and second values

© .
16

Get, set and display methods of Time


Class Time has
• 4 set methods
– setTime(int h, int m, int s)
– setHour(int h)
– setMinute(int m)
– setSecond(int s)
• 4 get methods
– int getHour()
– int getMinute()
– int getSecond()
– Time getTime()
• 2 display methods
– toString()
– toUniversalString()
© .
1 // Fig. 8.5: [Link] 17
2
3
Outline
// Time2 class declaration with overloaded constructors.

4 public class Time2


5 {
6 private int hour; // 0 - 23 [Link]
7 private int minute; // 0 - 59
8 private int second; // 0 - 59
9
10 // Time2 no-argument constructor: initializes each instance variable (1 of 4)
11 // to zero; ensures that Time2 objects start in a consistent state
12 public Time2()
No-argument constructor
13 {
14 this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
15 } // end Time2 no-argument constructor
16
17 // Time2 constructor: hour supplied, minute and second defaulted to 0
18 public Time2( int h )
Invoke three-argument constructor
19 {
20 this( h, 0, 0 ); // invoke Time2 constructor with three arguments
21 } // end Time2 one-argument constructor
22
23 // Time2 constructor: hour and minute supplied, second defaulted to 0
24 public Time2( int h, int m )
25 {
26 this( h, m, 0 ); // invoke Time2 constructor with three arguments
27 } // end Time2 two-argument constructor
28
© .
29 // Time2 constructor: hour, minute and second supplied 18
30
31
Outline
public Time2( int h, int m, int s )
{ Call setTime method
32 setTime( h, m, s ); // invoke setTime to validate time
33 } // end Time2 three-argument constructor
34
[Link]
35 // Time2 constructor: another Time2 object supplied
36 public Time2( Time2 time ) Constructor takes a reference to another
37 { Time2 object as a parameter
38 // invoke Time2 three-argument constructor
39 this( [Link](), [Link](), [Link]() ); (2 of 4)
40 } // end Time2 constructor with a Time2 object argument
41 Could have directly accessed instance
42 // Set Methods variables of object time here
43 // set a new time value using universal time; ensure that
44 // the data remains consistent by setting invalid values to zero
45 public void setTime( int h, int m, int s )
46 {
47 setHour( h ); // set the hour
48 setMinute( m ); // set the minute
49 setSecond( s ); // set the second
50 } // end method setTime
51

© .
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

Examples of time object creations

Time t1 = new Time(); // 00:00:00


// 00:00:00

Time t2 = new Time( 2 ); // 02:00:00


// 02:00:00
Time t3 = new Time( 21, 34 ); // 21:34:00
// 21:34:00
Time t4 = new Time( 12, 25, 42 ); // 12:25:42
// 12:25:42
Time t5 = new Time( 27, 74, 99 ); // 00:00:00
// 00:00:00
Time t6 = new Time( t4 ); // 12:25:42
// 12:25:42

[Link]( 12, 25, 42 ); // 12:25:42


// 12:25:42

[Link]( 6, 11, 0 ); // 06:11:00


// 06:11:00

[Link]( 11, 0, 0 ); // 11:00:00


// 11:00:00

© .
22

Test class for using Time2


1 // Fig. 8.6: [Link]
2 // Overloaded constructors used to initialize Time2 objects.
Time2Test.
3
4 public class Time2Test
java
5 {
6 public static void main( String args[] )
7 { (1 of 3)
8 Time2 t1 = new Time2(); // 00:00:00
9 Time2 t2 = new Time2( 2 ); // 02:00:00
10 Time2 t3 = new Time2( 21, 34 ); // 21:34:00
11 Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42
12 Time2 t5 = new Time2( 27, 74, 99 ); // 00:00:00
13 Time2 t6 = new Time2( t4 ); // 12:25:42
14
15 [Link]( "Constructed with:" );
16 [Link]( "t1: all arguments defaulted" );
17 [Link]( " %s\n", [Link]() );
18 [Link]( " %s\n", [Link]() );
19

© .
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

38 [Link]( "t6: Time2 object t4 specified" );


39 [Link]( " %s\n", [Link]() );
40 [Link]( " %s\n", [Link]() ); Time2Test.
41 } // end main
java
42 } // end class Time2Test

t1: all arguments defaulted


00:00:00 (3 of 3)
12:00:00 AM
t2: hour specified; minute and second defaulted
02:00:00
2:00:00 AM
t3: hour and minute specified; second defaulted
21:34:00
9:34:00 PM
t4: hour, minute and second specified
12:25:42
12:25:42 PM
t5: all invalid values specified
00:00:00
12:00:00 AM
t6: Time2 object t4 specified
12:25:42
12:25:42 PM

© .
25

2.3 Controlling Access to Members


• Access modifiers (public, protected, default and private)
control access to a class’s variables and methods.
• Primary purpose of public methods is freely access a class
from any other class.

• Another reason is to allow for polymorphism and inheritance.


• When methods are public, they can be overridden by
subclasses, enabling different classes to provide specific
implementations of the same method.

© .
26

Controlling Access to Members

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

Controlling Access to Members

© .
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

[Link]: hour has private access in Time1


[Link] = 7; // error: hour has private access in Time1
^
[Link]: minute has private access in Time1
[Link] = 15; // error: minute has private access in Time1
^
[Link]: second has private access in Time1
[Link] = 30; // error: second has private access in Time1
^
3 errors
© .
29

2.4 Referring to the Current Object’s


Members with "this" Reference
An object can reference to itself with keyword this
– non-static methods implicitly use this when referring
to the object’s instance variables and
– this can be used to access instance variables even when
they are shadowed by local variables

© .
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

Using this to access the object’s instance variables

© .
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

Common Programming Error 2.2

• It is a syntax error when this is used to call


another constructor if that call is not the first
statement.
• It is also a syntax error when a method attempts
to invoke a constructor directly via this.

© .
33

Common Programming Error 2.3


• A constructor can call methods of the class.
• Be aware that the instance variables might not
yet be in a consistent state, because the
constructor is in the process of initializing the
object.
• Using instance variables before they have been
initialized properly is a logic error.

© .
34

Software Engineering Observation 2.4

• If an object has a reference to another object of


the same class, it can access all data and
methods (including private ones) of that object

© .
35
public class Person {
private String name;

public Person(String name) {


[Link] = name;
}

// Method to compare names of two Person objects


public boolean hasSameName(Person other) {
return [Link]([Link]); // Accessing private field 'name' of 'other' object
}

public static void main(String[] args) {


Person person1 = new Person("Alice");
Person person2 = new Person("Alice");

// person1 can access the private 'name' field of person2


if ([Link](person2))
[Link]("Both persons have the same name.");
else
[Link]("The names are different.");
}
}
© .
36

2.5 Default or No-Argument Constructors

• Every class must have at least one constructor


– if no constructors are declared, the compiler will create
a default constructor
• do not takes arguments and initializes instance variables
to their initial values (default values)
– default values are;
• 0 ➔ for primitive numeric types
• false ➔ for boolean values
• null ➔ for reference types

© .
37

Common Programming Error 2.4

• If none of the constructors of a class is


no-argument (default) constructor and a program
attempts to call the parameterless constructor to
create an object, a compilation error occurs.

© .
38

public class MyClass {


private int value;

// Parameterized constructor
public MyClass(int value) {
[Link] = value;
}

// Another parameterized constructor


public MyClass(String stringValue) {
[Link] = [Link](stringValue);
}

// Getter method
public int getValue() {
return value;
}

© .
39

public static void main(String[] args) {


// Attempting to call a no-argument constructor (which doesn't exist)

MyClass obj = new MyClass(); // Compilation error here

// Creating objects using the available constructors


MyClass obj1 = new MyClass(42);
MyClass obj2 = new MyClass("123");

// Getting values from the objects


[Link]("Value of obj1: " + [Link]()); // Output: 42
[Link]("Value of obj2: " + [Link]()); // Output: 123
}
}

© .
40

Software Engineering Observation 2.6

• Java allows a method of the class besides its constructors


to have the same name as the class (but, it is not a good
idea) and to specify return types.
• Such methods are not constructors ! and will not be
called when an object of the class is instantiated.
• How Java differentiates methods and constructors?
• constructors do not have a return type, even void
• while creating an object new keyword is used before the constructor

© .
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.

▪ Composition represents a "has-a" relationship, indicating


that an object is composed of other objects.

▪ A class contains instance of another class as an attribute:


• a Car has-a Engine
• a Library has-a Book

© .
43

Software Engineering Observation 2.9

One form of software reuse is


composition, in which a class has
members which references to
objects of other classes.

© .
1 // Fig. 8.7: [Link] 44

2 // Date class declaration.


3
4 public class Date
[Link]
5 {
6 private int month; // 1-12 (1 of 3)
7 private int day; // 1-31 based on month
8 private int year; // any year
9
10 // constructor: call checkMonth to confirm proper value for month;
11 // call checkDay to confirm proper value for day
12 public Date( int theMonth, int theDay, int theYear )
13 {
14 month = checkMonth( theMonth ); // validate month
15 year = theYear; // could validate year
16 day = checkDay( theDay ); // validate day
17
18 [Link](
19 "Date object constructor for date %s\n", this );
20 } // end Date constructor
21

© .
22 // utility method to confirm proper month value 45

23 private int checkMonth( int testMonth ) Validates month value


24 {
25 if ( testMonth > 0 && testMonth <= 12 ) // validate month
[Link]
26 return testMonth;
27 else // month is invalid (2 of 3)
28 {
29 [Link](
30 "Invalid month (%d) set to 1.", testMonth );
31 return 1; // maintain object in consistent state
32 } // end else
33 } // end method checkMonth
34
35 // utility method to confirm proper day value based on month and year
36 private int checkDay( int testDay ) Validates day value
37 {
38 int daysPerMonth[] =
39 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
40

© .
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

Leap year problem

• A year is a leap year if


– it is divided by 4
– it is not not divided by 100 (a century year)
– but it is divided by 400

© .
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

Date object constructor for date 7/24/1949


Date object constructor for date 3/12/1988
Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949

© .
50

2.7 Garbage Collection and finalize Method


• Garbage collection
– JVM marks an object for garbage collection when there are no
more references to that object

•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

Garbage Collection and finalize Method


– finalize is called implicitly (automatically) by the garbage
collector when it performs termination housekeeping
– finalize releases resources and perform cleanup actions
like closing files, releasing network connections, or freeing up
memory associated with the object

© .
52
public class FinalizeExample {
public FinalizeExample() {
[Link]("Object created");
}

protected void finalize() { // finalize() method


[Link]("finalize() method called");
}

public static void main(String[] args) {


FinalizeExample obj = new FinalizeExample();

obj = null; // Dereference obj to make it eligible for garbage collection

// Request garbage collection


[Link](); Output :
Object created
[Link]("Main method completed"); Main method completed
} finalize() method called
}

© .
53

2.8 static Class Members

•static fields
– also known as class variables

– represents class-wide information

– 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

– can be accessed with the class name or an object name

– must be initialized in their declarations, or else the compiler


will initialize it with a default value
© .
54

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

11 // initialize employee, add 1 to static count and


12 // output String indicating that constructor was called
13 public Employee( String first, String last )
14 { increment static field
15 firstName = first;
lastName = last;

18 count++; // increment static count of employees


19 [Link]( "Employee constructor: %s %s; count = %d”,
20 firstName, lastName, count );
21 } // end Employee constructor

© .
57

Class Employee (cont.)


23 // subtract 1 from static count when garbage
24 // collector calls finalize to clean up object;
25 // confirm that finalize was called
26 protected void finalize() declare method finalize
27 {
28 count--; // decrement count of employees
29 [Link]( "Employee finalizer: %s %s;count = %d\n",
30 firstName, lastName, count );
31 } // end method finalize

© .
58

Class Employee (cont.)


33 // get first name
34 public String getFirstName()
35 {
36 return firstName;
37 } // end method getFirstName

39 // get last name


40 public String getLastName()
41 { declare static method getCount to
42 return lastName; get static field count
43 } // end method getLastName

45 // static method to get static count value


46 public static int getCount()
47 {
48 return count;
49 } // end method getCount
50 } // end class Employee
© .
59

In main method of EmployeeTest


• Get counter of Employee class
static method without any object
• Generate two employees (object)
call getCounter on each employee and
with using class name
• Print employee information
first-last names of the two employees
• Assign two reference variable to null
e1 = null; e2 = null;
no more reference (access) to employee objects
• Ask garbage collector to distroy objects in memory
• Print number of employees after garbage collector
© .
60

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

Class EmployeeTest (cont.)


23 // get names of Employees
24 [Link]( "\nEmployee 1: %s %s\nEmployee 2:
%s %s\n\n",
25 [Link](), [Link](),
26 [Link](), [Link]() );
27
28 // there is only one reference to each Employee,
29 // so the following two statements cause the JVM to mark
30 // each Employee object for garbage collection

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

Call static method gc of class System to indicate


that garbage collection should be attempted

© .
62

Class EmployeeTest (cont.)


36 // show Employee count after calling garbage collector
37 // count displayed may be 0, 1 or 2 based on whether
38 // garbage collector executes immediately and number of
39 // Employee objects collected

40 [Link]( "\nEmployees after [Link](): %d\n",


[Link]() );
41 } // end main
42 } // end class EmployeeTest

Call static method getCount

© .
63

static Class Members (cont.)


• Static methods cannot access non-static class members.
– Static members belong to the class itself, not to any
individual object. This means, they are created once when the
class is loaded into memory, even before any objects are
created.
– Non-static members belong to individual objects.
They are created and occupy memory only when an object
is instantiated using the new keyword.
– Static methods cannot access instance (non-static) members
directly because those members belong to objects that may
not exist yet. Since static methods are not tied to any object,
they do not have access to object-specific data.
– Furthermore, the keyword "this" means "current object,"
But in static methods, there is no current object, so this
cannot be used. © .
64

public class Bank {


private String branchName;

public Bank(String branchName) {


[Link] = branchName;
}

// Static method: Common information valid for all bank branches


public static void generalInfo() {
[Link](" Bank is open between 09:00-17:00 on weekdays.");

// The following line is ERROR! Because, the static method


// cannot access the object-specific variable branchName :
[Link]("Branch Name : " + branchName); // Syntax Error!

// The following line is ERROR! Because, this cannot be used:


[Link]("Branch Name: " + [Link]); // Syntax Error!
}
© .
65

// Non-static method: depending on the branch instance (object)


public void branchInfo() {
[Link]("This Branch: " + branchName);
}

public static void main(String[] args) {


[Link](); // Sınıfa ait bilgi çağrılır

Bank branch1 = new Bank("Kadıköy Şubesi");


[Link](); // Nesneye ait bilgi çağrılır
}
}

© .
66

Common Programming Error 2.7


• A compilation error occurs if a static method
calls an instance method (non-static) and
instance variable in the same class by using
only the method name.

© .
67

Common Programming Error 2.8

Refering to this in a static method is also a


compilation error.

© .
68

2.9 static import


•static import declarations
– normal import declaration brings classes or packages into your
current source code file, allowing you to use them without having to
fully qualify their names,
– static import declaration imports static members from classes,
allowing them to be used without class qualification

© .
69

1 // Fig. 8.14: [Link] static import on demand


2 // Using static import to import static methods of class Math.

3 import static [Link].*; StaticImportTest


4
.java
5 public class StaticImportTest
Use Math’s static methods and
6 {
instance variable without
7 public static void main( String args[] ) preceding them with Math.
8 {

9 [Link]( "sqrt( 900.0 ) = %.1f\n", sqrt( 900.0 ) );

10 [Link]( "ceil( -9.8 ) = %.1f\n", ceil( -9.8 ) );

11 [Link]( "log( E ) = %.1f\n", log( E ) );

12 [Link]( "cos( 0.0 ) = %.1f\n", cos( 0.0 ) );

13 } // end main

14 } // end class StaticImportTest

sqrt( 900.0 ) = 30.0


ceil( -9.8 ) = -9.0
log( E ) = 1.0
cos( 0.0 ) = 1.0

© .
70

Common Programming Error 2.9

A compilation error occurs if a program attempts


to import static methods or fields that have the
same name from two or more classes.

© .
71

example

© .
72

2.10 final Instance Variables

• Principle of least privilege (POLP)


– Users should have minimum access rights and permissions
necessary to perform their tasks

•final instance variables


– keyword final
• specifies that a variable is not modifiable (is a constant)
– final instance variable can be initialized at its declaration
• if it is not initialized in declarations, it must be initialized in all
constructors

© .
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

Before incrementing: total = 0

After increment 1: total = 5


After increment 2: total = 10
After increment 3: total = 15

© .
75

Common Programming Error 2.10

Attempting to modify a final instance variable


after its initialization is a compilation error.

© .
76

Software Engineering Observation 2.14

• A final field should also be declared static


• Making the field static enables all objects of the
class to share the final field.

© .
77

2.11 Sending simple types or references to


methods

• When you send parameters to methods, you essentially


pass values or references to those methods

• The behavior depends on whether you are working with


primitive types (simple types) or reference types (objects)

// Output will be ➔ 5

© .
78

Sending simple types or references to methods

// Output will be ➔ Alice

© .
79

Sending simple types or references to methods

• Exp: Two integer exchange program: TestExchange1


– in the main method of TestExchange1 two integers are
created (int a=2, b=3)

– call the exchange1 method – expected to interchange the


values
• a  3 and b  2

© .
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);

} // end of method main

© .
81

method exchange1
public static void exchange1(int x, int y) {

[Link](“in method before exchange:%8d


%8d\n”,x,y);
int temp = x;
x = y;
y = temp;
[Link](“in method after exchange:%8d
%8d\n”,x,y);

} // end of method exchange1


OUTPUT :
} // end of class TestChange1 in main before exchange1: 2 3
in method before exchange: 2 3
in method after exchange: 3 2
in main after exchange1: 2 3

© .
82

class Int
Define a new type for integer

public class Int {


private int val;
public Int(int v) {
val = v;
}
public int getVal() {
return val;
}
public void setVal(int v) {
val = v;
}
} // end of class Int

© .
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);

[Link](“in main after exchange2:%8d


%8d\n”,[Link](),[Link]());

} // end of method main

© .
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]());

} // end of method exchange2 OUTPUT :


} // end of class TestExchange2 in main before exchange2: 2 3
in method before exchange: 2 3
in method after exchange: 3 2
in main after exchange2: 3 2

© .
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);

[Link](“in main after exchange3:


%8d %8d\n”, [Link](), [Link]());

} // end of method main


© .
86

method exchange3
public static void exchange3(Int x, Int y) {
[Link](“in method before exchange:
%8d %8d\n”, [Link](), [Link]());

Int temp = x; // object from Int class


x = y;
y = temp;

[Link](“in method after exchange:


%8d %8d\n”, [Link](), [Link]());
OUTPUT :
} // end of method exchange3in main before exchange3: 2 3
} // end of class TestExchange3in method before exchange: 2 3
in method after exchange: 3 2
in main after exchange3: 2 3

© .
87

Explanations
• After executing
temp = x;
x = y;
y = temp;

• The local variables x and y‘s values are changed

• But not the integer type numbers within these objects !!

• So, this is not a sucessful exchanging

© .
88

2.12 Data Abstraction and Encapsulation

• Data abstraction
– Information hiding
• Classes normally hide the details of their implementation
from their clients

© .
89

Data Abstraction and Encapsulation

• Data abstraction
– Abstract data types (ADTs)
• You can define your classes based on the behaviors of their
operations, without knowing implementation details.

• ADT only mentions what operations are to be performed,


but not how these operations will be implemented.

• You don’t know how data will be organized in memory and


which algorithms will be used for implementing the operations.

• It is called “abstract” because it gives an


implementation-independent view.

© .
90

Data Abstraction and Encapsulation

• 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);

[Link]("Point 1: (" + [Link]() + ", " + [Link]() + ")");


[Link]("Point 2: (" + [Link]() + ", " + [Link]() + ")");

double distance = [Link](point2);

[Link]("Distance between Point 1 and Point 2: " + distance);


}
}

Output of the program:


Point 1: (3.0, 4.0)
Point 2: (0.0, 0.0)
Distance between Point 1 and Point 2: 5.0

© .
93

Data Abstraction and Encapsulation (Cont.)

• 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)

– Internal data representation is hidden


• Clients only see the ability to enqueue
and dequeue items

© .
94

Data Abstraction and Encapsulation (Cont.)

• 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

– Internal data representation is hidden


• Clients only see the ability to
push and pop items
© .
95

Data Abstraction and Encapsulation (Cont.)

• 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

2.13 Creating Packages


• Package in Java is used to group related classes.

• Think of it as a folder in a file directory.

• We use packages to avoid name conflicts and to write a better


maintainable code.
– there can be two Employee classes in different packages

• Package provides controlled access:


protected and default have package level access control.
• protected ➔ accessible by classes in the same package and
its subclasses (even if those subclasses are in different
packages).
• default (without any access modifier) ➔ accessible by classes
in the same package only.
© .
97
package [Link];
package declaration

public class MyClass {


public void publicMethod() { When we compile [Link] file,
[Link]("Public method"); the class will be placed in the following
} package directory

protected void protectedMethod() {


[Link]("Protected method");
}
Java compiler creates
appropriate directories according to
void defaultMethod() { the class's package declaration
[Link]("Default method");
}
}

© .
98

package [Link];

public class TestClass {


public void testMethods() {
MyClass myClass = new MyClass();

// Calling the public method


[Link](); // This will work

// Calling the protected method


[Link](); // This will work as TestClass is in the same package

// Calling the default method


[Link](); // This will work as TestClass is in the same package
}

public static void main(String[] args) {


TestClass test = new TestClass();
[Link]();
}
}
© .
package [Link]; // different package 99

import [Link]; // import MyClass

public class AccessTest {


public void testMethods() {
MyClass myClass = new MyClass();

// Calling public method


[Link](); // This will work

// Calling protected method


[Link](); // Compile error: protected method not visible

// Calling default method


[Link](); // Compile error: default method not visible
}

public static void main(String[] args) {


AccessTest test = new AccessTest();
[Link]();
}
} © .
100

Creating Packages

– Import the reusable class into a program


• Single-type-import declaration
– imports a single class
– example: import [Link];

• Type-import-on-demand declaration
– imports all classes in a package
– example: import [Link].*;

© .
101

Common Programming Error 2.12

• Using the import declaration

import java.*;
causes a compilation error.

• You must specify the exact name of the package


from which you want to import classes.

© .
102

2.14 Package Access

• Package access
– When a class, method or variable is declared without any
access modifier (e.g., class MyClass), it has package access.

– This has no effect if the program consists of one class

– If the program contains multiple classes from the same package


• package access allows access to members within the same package
(i.e., within the same directory or package name)
• members with package access are not visible to classes in other
packages, including subclasses in other packages.

© .
103

// class with package access instance variables


class PackageData {
int number = 0; // package-access instance variable
String string = "Hello"; // package-access instance variable
Package-access instance variables

// return PackageData object String representation


public String toString() {
return [Link]("number: %d; string: %s", number, string);
}
}

© .
104
public class PackageDataTest {
public static void main(String[] args) {
PackageData packageData = new PackageData();

// output String representation of packageData


[Link]("After instantiation:%n%s%n", packageData);

// change package access data in packageData object


[Link] = 77; Can directly access package-access members
[Link] = "Goodbye";

// output String representation of packageData


[Link]("%nAfter changing values:%n%s%n", packageData);
}
}
© .
105

2.15 enum (Enumeration)

• Enumeration (or enum for short) is a data type that


represents a fixed set of named values.
• enum is used to define a collection of constants or a
limited set of related values.

• Makes code more readable, self-documenting and


type-safe.

© .
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

public class EnumConstructorExample { // Overloaded constructor


public enum Day { Day() {
MONDAY("Start of the week"), [Link] = "No description";
TUESDAY("Second day"), }
WEDNESDAY("Midweek"), public String getDescription() {
THURSDAY("Almost weekend"), return description;
FRIDAY("Weekend starts"), }
SATURDAY("Weekend"), }
SUNDAY("End of the week");
public static void main(String[] args) {
private String description;
for (Day day : [Link]()) {
// Enum constructor with parameter [Link](day + ": " +
[Link]());
Day(String description) {
[Link] = description;
}
}
}
}

© .
109

Output of the Program


MONDAY: Start of the week
TUESDAY: Second day
WEDNESDAY: Midweek
THURSDAY: Almost weekend
FRIDAY: Weekend starts
SATURDAY: Weekend
SUNDAY: End of the week

© .
110

Enumerations: example
• Create a Java program (MonthEnum class) that defines
an enum type representing the months of the year.

• Each month should have an abbreviation and the number


of days.

• Demonstrate the use of the enum by printing information


about the current month and iterating over all months to
display their details.

© .
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);

private String abbreviation;


private int days;
© .
112

// Constructor for the Month enum


Month(String abbreviation, int days) {
[Link] = abbreviation; [Link]
[Link] = days;
} (2 of 3)

// Method to get the abbreviation


public String getAbbreviation() {
return abbreviation;
}

// Method to get the number of days in the month


public int getDays() {
return days;
}
} // end of enum declaration

© .
113

public static void main(String[] args) {


// Using the Month enum with constructors and methods
Month currentMonth = [Link]; [Link]
[Link]("Current month: " + currentMonth);
[Link]("Abbreviation: " + [Link]()); (3 of 3)
[Link]("Number of days: " + [Link]());

// 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

27 public String getTitle()


28 {
29 return title;
[Link]
30 } // end method getTitle
31
32 // accessor for field copyrightYear (2 of 2)
33 public String getCopyrightYear()
34 {
35 return copyrightYear;
36 } // end method getCopyrightYear
37 } // end enum Book

© .
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:

JHTP6 Java How to Program 6e 2005


CHTP4 C How to Program 4e 2004
IW3HTP3 Internet & World Wide Web How to Program 3e 2004
CPPHTP4 C++ How to Program 4e 2003 [Link]
VBHTP2 Visual Basic .NET How to Program 2e 2002
CSHARPHTP C# How to Program 2002

Display a range of enum constants: (2 of 2)


JHTP6 Java How to Program 6e 2005
CHTP4 C How to Program 4e 2004
IW3HTP3 Internet & World Wide Web How to Program 3e 2004
CPPHTP4 C++ How to Program 4e 2003

© .
119

Common Programming Error 8.6

• In an enum declaration, it is a syntax error to


declare enum constants after the enum type’s
constructors, fields and methods in the enum
declaration.

© .
120

Incorrect enum Declaration


(with Syntax Error)
public enum Color {
// Constructors, fields, and methods public int getB() {
// are declared first return b;
private final int r; }
private final int g;
private final int b; // enum constants are declared after fields
// and methods, causing a syntax error
Color(int r, int g, int b) {
RED(255, 0, 0),
this.r = r;
GREEN(0, 255, 0),
this.g = g;
BLUE(0, 0, 255);
this.b = b;
}
}

?
public int getR() {
return r;
}

public int getG() {


return g;
} © .
121

Correct enum Declaration


public enum Color {
// Enum constants are declared first // Methods
RED(255, 0, 0), public int getR() {
GREEN(0, 255, 0), return r;
BLUE(0, 0, 255); }

// Fields public int getG() {


private final int r; return g;
private final int g; }
private final int b;
public int getB() {
// Constructor return b;
Color(int r, int g, int b) { }
this.r = r; }
this.g = g;
this.b = b;
}

© .

You might also like