Polymorphic copy: Difference between revisions

added java
(Polymorphic copy)
 
(added java)
Line 62:
Copied S
</pre>
 
=={{header|Java}}==
Here we implement a "copy" method once in the base class because there is by default no public way to copy an object from outside the class in Java. (There is a protected, not public, "clone" method inherited from Object.)
<java>class T implements Cloneable {
public String name() { return "T"; }
public T copy() {
try {
return (T)super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
 
class S extends T {
public String name() { return "S"; }
}
 
public class PolymorphicCopy {
public static T copier(T x) { return x.copy(); }
public static void main(String[] args) {
T obj1 = new T();
S obj2 = new S();
System.out.println(copier(obj1).name()); // prints "T"
System.out.println(copier(obj2).name()); // prints "S"
}
}</java>
Anonymous user