General Java Questions II
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());
}
return ac;
}
}
Note that the class AnotherClass, that extends MyClass, automatically becomes
Cloneable, because MyClass is Cloneable.
Also note, that super.clone() always returns an Object of the type of the actual object,
although the superclass doesn t know anything about that sub class. The reason is,
that Object.clone() is a native method, which just allocates new memory for the new
object and copies the bytes to that memory. Native code has it s own ways of finding
out which type to return ; )
Karl Schmidt
I was just wondering about the usefulness of Interfaces...
I was just wondering about the usefulness of Interfaces. I was under the impression
that interfaces could be used to perform multiple inheritance. But an interface only
declares a method in a very abstract way.
A class that implements an interface needs to define its own implementation of a
certain method. What is the use of having an interface when nothing is being
gained...?
Answer: If two classes implements the same interface, you can get a reference to the
interface instead of the effective class without bother what class are you managing.
This is very useful in RMI (for example) or in any condition when you have to take an
object without knowing exactly his class, but only the interface that it implement.
file:///F|/a_jsite/350_tips/general_java II.htm (12 of 14) [2001 07 08 11:24:53]
footer
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved