Java Reference
In-Depth Information
10.1 Introduction
The focus of this chapter is on class design and explores the differences between
procedural programming and object-oriented programming.
Key
Point
The preceding two chapters introduced objects and classes. You learned how to define classes,
create objects, and use objects from several classes in the Java API (e.g., Date , Random ,
String , StringBuilder , and Scanner ). This topic's approach is to teach problem solving
and fundamental programming techniques before object-oriented programming. This chapter
shows how procedural and object-oriented programming differ. You will see the benefits of
object-oriented programming and learn to use it effectively.
We will use several examples to illustrate the advantages of the object-oriented approach.
The examples involve designing new classes and using them in applications. We first intro-
duce some language features supporting these examples.
10.2 Immutable Objects and Classes
You can define immutable classes to create immutable objects. The contents of
immutable objects cannot be changed.
Key
Point
Normally, you create an object and allow its contents to be changed later. However, occasion-
ally it is desirable to create an object whose contents cannot be changed once the object has
been created. We call such an object an immutable object and its class an immutable class .
The String class, for example, is immutable. If you deleted the set method in the
CircleWithPrivateDataFields class in Listing 8.9, the class would be immutable,
because radius is private and cannot be changed without a set method.
If a class is immutable, then all its data fields must be private and it cannot contain public
set methods for any data fields. A class with all private data fields and no mutators is not
necessarily immutable. For example, the following Student class has all private data fields
and no set methods, but it is not an immutable class.
VideoNote
Immutable objects and this
keyword
immutable object
immutable class
1
2
public class Student {
Student class
private int id;
3
4
5
6 public Student( int ssn, String newName) {
7 id = ssn;
8
9 dateCreated = new java.util.Date();
10 }
11
12
private String name;
private java.util.Date dateCreated;
name = newName;
public int getId() {
13
return id;
14 }
15
16
public String getName() {
17
return name;
18 }
19
20
21
public java.util.Date getDateCreated() {
return dateCreated;
22 }
23 }
As shown in the following code, the data field dateCreated is returned using the
getDateCreated() method. This is a reference to a Date object. Through this reference,
the content for dateCreated can be changed.
 
 
 
 
Search WWH ::




Custom Search