我们知道Object基类有如下的方法:
问题一:
为什么唯独clone方法,在源码中要定义成protected呢?其他定义成public的呢?
问题二:
finalize()这个方法好像在项目中很少被用到,但是它能够被定义到基类当中,说明其重要性是很高的,那么这个具体如何使用?在什么情况下,必须使用,非用不可呢??
// 对象相关
getClass()
clone() - protected
toString()
equals(Object)
hashCode()
// 线程相关
notify()
notifyAll()
wait([long[, int]])
// GC相关
finalize()
This is to prevent direct calls from outside the class.
Because of the
clone
方法要先要实现Cloneable
interface, then override the clone() method.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.
If you use java to call c, C++, or windows api, this is actually calledSo, while many people know the
constructor
, they forget the correspondingdestructor
. (As mentioned above, Java will automatically release memory.)构造函数
的同时,却忘记了对应的析构函数
。(上文提到过,Java会自动释放内存。)但是:
java
释放的是java
申请的内存。如果你用java调用了c、C++,或者windows api的时候,其实这叫
JNI(Java Native Interface)
,这里申请的内存,java是无法自动释放的,那么就可能需要通过finalize
But:java
releases the memory requested byjava
.JNI (Java Native Interface)
. Java cannot automatically release the memory applied here. Then you may need to release it in parallel throughfinalize
. 🎜Simply put, it works like a destructor. 🎜