Answer the question
In order to leave comments, you need to log in
How does the object class work in this code?
How does the object class work? I don't understand why he's here.
public class Main {
public static void main(String[] args) { //throws - exception
Date x,y;
x=new Date();
Object clone = x.clone();
System.out.println(clone);
}
}
Answer the question
In order to leave comments, you need to log in
Object clone = x.clone();
This is a clone (copy) of an object of the Date class.
Then it needs to be cast to the Date type
. Why does clone() return an Object ? - because this method is inherited from the Object class, and since all types in Java inherit the Object class, therefore clone() must return a common type for all types - Object
First you need to figure out why you still need to override the clone () method, and not use the inherited native implementation of this method. The point is that the basic clone method only performs a shallow copy. Only the values of the class fields will be copied. For primitive types (int, byte, char), everything will be fine, but if they are arrays, collections, objects (for example Date), or your types, then only references to them will be copied. As a result of cloning, we will have two objects whose fields refer to the same fields, and through these fields we can influence all objects that were cloned:
class TestClone implements Cloneable {
private Date date = new Date();
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
TestClone a = new TestClone();
TestClone b = (TestClone) a.clone();
System.out.println(a.getDate());
System.out.println(b.getDate());
b.getDate().setYear(0);
System.out.println(a.getDate());
System.out.println(b.getDate());
// Fri Jul 10 23:13:47 EEST 2015
// Fri Jul 10 23:13:47 EEST 2015
// изменили один, а поменялось два
// Tue Jul 10 23:13:47 EET 1900
// Tue Jul 10 23:13:47 EET 1900
class TestClone implements Cloneable {
private Date date = new Date();
private String s = "string"; // этот не нужно клонировать
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
protected Object clone() throws CloneNotSupportedException {
TestClone clone = (TestClone) super.clone();
if (this.date != null) {
clone.date = (Date) this.date.clone();
}
return clone;
}
}
Fri Jul 10 23:25:16 EEST 2015
Fri Jul 10 23:25:16 EEST 2015
// теперь это действительно клоны
Fri Jul 10 23:25:16 EEST 2015
Tue Jul 10 23:25:16 EET 1900
TestClone с = new TestClone();
if (с instanceof Cloneable) {
System.out.println("ок, меня можно клонировать");
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question