java - clone()方法疑问
天蓬老师
天蓬老师 2017-04-18 09:34:52
0
1
615

我们知道Object基类有如下的方法:
问题一:
为什么唯独clone方法,在源码中要定义成protected呢?其他定义成public的呢?
问题二:
finalize()这个方法好像在项目中很少被用到,但是它能够被定义到基类当中,说明其重要性是很高的,那么这个具体如何使用?在什么情况下,必须使用,非用不可呢??



// 对象相关
getClass()
clone() - protected
toString()
equals(Object)
hashCode()

// 线程相关
notify()
notifyAll()
wait([long[, int]])

// GC相关
finalize()
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
大家讲道理

This is to prevent direct calls from outside the class.

Because of the clone方法要先要实现Cloneable interface, then override the clone() method.

public class Test01 implements Cloneable{  
}

If you don’t use this function often, you may not have enough project experience

If you have relatively low-level programming experience (such as C language), you may pay more attention to the release of memory, then the release of resources, etc. Application and release must occur in pairs. However, due to the virtual machine in Java, there is a garbage collection mechanism, and you may have never paid attention to the issue of memory release. In fact, you don't really need to pay attention to this.
So, while many people know the constructor, they forget the corresponding destructor. (As mentioned above, Java will automatically release memory.) 构造函数的同时,却忘记了对应的析构函数。(上文提到过,Java会自动释放内存。)
但是:
java释放的是java申请的内存。
如果你用java调用了c、C++,或者windows api的时候,其实这叫JNI(Java Native Interface),这里申请的内存,java是无法自动释放的,那么就可能需要通过finalizeBut:
java releases the memory requested by java.

If you use java to call c, C++, or windows api, this is actually called JNI (Java Native Interface). Java cannot automatically release the memory applied here. Then you may need to release it in parallel through finalize. 🎜Simply put, it works like a destructor. 🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template