Effective Java


immutable classes should never provide a



Download 2,19 Mb.
Pdf ko'rish
bet62/341
Sana11.07.2022
Hajmi2,19 Mb.
#776765
1   ...   58   59   60   61   62   63   64   65   ...   341
Bog'liq
Effective Java

immutable classes should never provide a 
clone
 method
because it would
merely encourage wasteful copying. With that caveat, here’s how a 
clone
method
for 
PhoneNumber
would look:
// Clone method for class with no references to mutable state
@Override public PhoneNumber clone() {
try {
return (PhoneNumber) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(); // Can't happen
}
}
In order for this method to work, the class declaration for 
PhoneNumber
would
have to be modified to indicate that it implements 
Cloneable
. Though 
Object
’s
clone
method returns 
Object
, this 
clone
method returns 
PhoneNumber
. It is legal


CHAPTER 3
METHODS COMMON TO ALL OBJECTS
60
and desirable to do this because Java supports 
covariant return types
. In other
words, an overriding method’s return type can be a subclass of the overridden
method’s return type. This eliminates the need for casting in the client. We must
cast the result of 
super.clone
from 
Object
to 
PhoneNumber
before returning it,
but the cast is guaranteed to succeed.
The call to 
super.clone
is contained in a 
try-catch
block. This is because
Object
declares its 
clone
method to throw 
CloneNotSupportedException
,
which is a 
checked exception
. Because 
PhoneNumber
implements 
Cloneable
, we
know the call to 
super.clone
will succeed. The need for this boilerplate indicates
that 
CloneNotSupportedException
should have been unchecked (Item 71).
If an object contains fields that refer to mutable objects, the simple 
clone
implementation shown earlier can be disastrous. For example, consider the 
Stack
class in Item 7:
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
this.elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
// Ensure space for at least one more element.
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
Suppose you want to make this class cloneable. If the 
clone
method merely
returns 
super.clone()
, the resulting 
Stack
instance will have the correct value in


ITEM 13: OVERRIDE CLONE JUDICIOUSLY
61
its 
size
field, but its 
elements
field will refer to the same array as the original
Stack
instance. Modifying the original will destroy the invariants in the clone and
vice versa. You will quickly find that your program produces nonsensical results
or throws a 
NullPointerException

This situation could never occur as a result of calling the sole constructor in
the 
Stack
class. 

Download 2,19 Mb.

Do'stlaringiz bilan baham:
1   ...   58   59   60   61   62   63   64   65   ...   341




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish