Ans : Cloning is process of creating a java object using the same another java object.
Example:
line 10: Class CloneMyObject
line 20:{
line 30: int x;
line 40: int y;
line 50: public static void main(String[] args)
line 60: {
line 70: CloneMyObject ob1 = new CloneMyObject();
line 80: ob1.x = 500;
line 90: ob1.y = 900;
line 100: System.out.println("ob1.x = "+ob1.x+" ob1.y = "+ob1.y);
line 110: CloneMyObject ob2 = (CloneMyObject ) ob1.clone();
line 120: System.out.println("ob2.x = "+ob2.x+" ob2.y = "+ob2.y);
line 130: }
line 140: }
Explanation : In line 110 we are cloning the object of class "CloneMyObject" but
above program will through an Exception :"java.lang.CloneNotSupportedException"
Reason : Because class Doesn't implement the interface marker interface "Cloneable"
So edit the line 10 like this : "Class CloneMyObject implements Cloneable"
Next Observation : In line 110 we are typecasting the created object to the
class "CloneMyObject."
Do we really need to typecast the new cloned object to class ?
Ans : YES, the method clone is present in the class Object, that creates
same like the object, on which the clone method called. and returns
the generic object, there we need to Typecast it Explicitly.
Then how come we get rid off it ?
Ans : Easy, we need to override the method "clone()" in your class,
to return the object of type of your class.
Example:
Class MyClassObject
{
int x ;
int y;
pubic static void main(String[] args)
{
MyClassObject mcb = new MyClassObject();
mcb.x = 50;
mcb.y = 90;
Syso(" "+mcb.x+" "+mcb.y);
MyClassObject mcb2 = mcb.clone();
Syso(" "+mcb2.x+" "+mcb2.y);
}
public MyClassObject clone()
{
return new MyClassObject ();
}
}
Explanation : Overriding the same method which is already present
in the super class , is called " Covariant return types" .
what is the Definition of Covariant return type ?
Ans : What this means is that a method in a subclass may return an object
whose type is a subclass of the type, returned by the method with the same
signature in the superclass. This feature removes the need for excessive type
checking and casting.
Question : What is Marker Interface ?
Ans: It is used to mark the classes which support certain capability
Question : What are all Market Interfaces in Java?
Ans: Clonable , Serializable , RandomAccess interface , SingleThreadModel.
Question : What is RandomAccess Interface ?
Answer : The
RandomAccess
interface identifies that a particular java.util.List
implementation has fast random access. Example :
List.get()
method is faster than repeated access using the Iterator.next()
method, then the List has fast random access.
No comments:
Post a Comment