Java Reference
In-Depth Information
15.18
Which of the following is the correct method header for the compareTo method in
the String class?
public int compareTo(String o)
public int compareTo(Object o)
15.19
Can the following code be compiled? Why?
Integer n1 = new Integer( 3 );
Object n2 = new Integer( 4 );
System.out.println(n1.compareTo(n2));
15.20 You can define the compareTo method in a class without implementing the
Comparable interface. What are the benefits of implementing the Comparable
interface?
15.21 True or false? If a class implements Comparable , the object of the class can invoke
the compareTo method.
15.7 The Cloneable Interface
The Cloneable interface defines the compareTo method for comparing objects.
Key
Point
Often it is desirable to create a copy of an object. To do this, you need to use the clone
method and understand the Cloneable interface.
An interface contains constants and abstract methods, but the Cloneable interface is a
special case. The Cloneable interface in the java.lang package is defined as follows:
package java.lang;
java.lang.Cloneable
public interface Cloneable {
}
This interface is empty. An interface with an empty body is referred to as a marker interface .
A marker interface does not contain constants or methods. It is used to denote that a class pos-
sesses certain desirable properties. A class that implements the Cloneable interface is
marked cloneable, and its objects can be cloned using the clone() method defined in the
Object class.
Many classes in the Java library (e.g., Date , Calendar , and ArrayList ) implement
Cloneable . Thus, the instances of these classes can be cloned. For example, the following code
marker interface
1 Calendar calendar = new GregorianCalendar( 2013 , 2 , 1 );
2 Calendar calendar1 = calendar;
3 Calendar calendar2 = (Calendar)calendar.clone();
4 System.out.println( "calendar == calendar1 is " +
5 (calendar == calendar1));
6 System.out.println( "calendar == calendar2 is " +
7 (calendar == calendar2));
8 System.out.println( "calendar.equals(calendar2) is " +
9 calendar.equals(calendar2));
displays
calendar == calendar1 is true
calendar == calendar2 is false
calendar.equals(calendar2) is true
In the preceding code, line 2 copies the reference of calendar to calendar1 , so calendar
and calendar1 point to the same Calendar object. Line 3 creates a new object that is the
 
 
Search WWH ::




Custom Search