General Java Questions I
Q: I try to copy an object of my own using the clone() method from
java.lang.Object, but this is a protected method so I can t use it. Is there some other
way to get my objective of duplicating an arbitrary object?
Answer: If you want to clone your object, you need to make it cloneable. To achieve
this, you need to do two things:
1. implement the interface Cloneable
2. override the method clone(), so that it 
a. becomes public
b. calls super.clone()
c. if necessary, clones any members, or
d. if a member can t be cloned, creates a new instance.
Simple example:
public MyClass implements Cloneable {
   int someNumber;
   String someString;
   public Object clone() {
   // primitives and Strings are no
   // problem
      return super.clone();
  }
}
In this case the method clone() of the class MyClass returns a new instance of
MyClass, where all members have exactly the same value. That means, the object
reference  someString  points to the same object. This is called a shallow
copy. In many cases this is no problem. Strings are immutable and you do not
need a new copy. But if you need new copies of members, you have to do it in
the clone() method. Here is another simple example:
public class SomeMember implements Cloneable {
   long someLong;
   public Object clone() {
      return super.clone();
   }
}
public AnotherClass extends MyClass {
    SomeMember someMember;
    public Object clone() {
        AnotherClass ac = (AnotherClass)(super.clone());
        if (someMember != null) {
            ac.someMember = (SomeMember)(someMember.clone());
file:///F|/a_jsite/350_tips/general_java I.htm (14 of 33) [2001 07 08 11:24:51]






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java web hosting

 

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved