JDK8中Object类提供的方法:

  1. package java.lang;
  2.  
  3. /**
  4. * Class {@code Object} is the root of the class hierarchy.
  5. * Every class has {@code Object} as a superclass. All objects,
  6. * including arrays, implement the methods of this class.
  7. *
  8. * @author unascribed
  9. * @see java.lang.Class
  10. * @since JDK1.0
  11. */
  12. public class Object {
  13.  
  14. private static native void registerNatives();
  15. static {
  16. registerNatives();
  17. }

  java虚拟机创造对象的一些基本操作:分配内存空间,定义变量,产生this指针等等。

1.子类是否可以继承父类的private属性和方法?

  1. package demo;
  2.  
  3. public class TestPrivate extends A{
  4.  
  5. public static void main(String[] args) {
  6. TestPrivate obj = new TestPrivate();
  7. obj.count; // The field A.count is not visible
  8. obj.out(); // The method out() from the type A is not visible
  9. }
  10.  
  11. }
  12. class A{
  13. private int count;
  14. private void out(){
  15. System.out.println("A private method");
  16. }
  17. }

  

  子类继承父类,但是父类的private属性和方法仍然属于父类所有,即子类并不具有该private属性和方法(只能看不能用),若想要同样的属性就需要自己重新定义或在父类中设置get,set方法。

2.native关键字解释

(https://www.cnblogs.com/KingIceMou/p/7239668.html)

Java平台有个用户和本地C代码进行互操作的API,称为Java Native Interface (Java本地接口)。使用native关键字说明这个方法是原生函数,也就是这个方法是用C/C++语言实现的,并且被编译成了DLL,由java去调用。这些函数的实现体在DLL中,JDK的源代码中并不包含,你应该是看不到的。对于不同的平台它们也是不同的。这也是java的底层机制,实际上java就是在不同的平台上调用不同的native方法实现对操作系统的访问的

native是与C++联合开发的时候用的!java自己开发不用的!

1。native 是用做java 和其他语言(如c++)进行协作时用的
也就是native 后的函数的实现不是用java写的
2。既然都不是java,那就别管它的源代码了,呵呵

native的意思就是通知操作系统,这个函数你必须给我实现,因为我要使用。
所以native关键字的函数都是操作系统实现的,java只能调用。

java是跨平台的语言,既然是跨了平台,所付出的代价就是牺牲一些对底层的控制,而java要实现对底层的控制,就需要一些其他语言的帮助,这个就是native的作用了

Java不是完美的,Java的不足除了体现在运行速度上要比传统的C++慢许多之外,Java无法直接访问到操作系统底层(如系统硬件等),为此Java使用native方法来扩展Java程序的功能。
  可以将native方法比作Java程序同C程序的接口,其实现步骤:
  1、在Java中声明native()方法,然后编译;
  2、用javah产生一个.h文件;
  3、写一个.cpp文件实现native导出方法,其中需要包含第二步产生的.h文件(注意其中又包含了JDK带的jni.h文件);
  4、将第三步的.cpp文件编译成动态链接库文件;
  5、在Java中用System.loadLibrary()方法加载第四步产生的动态链接库文件,这个native()方法就可以在Java中被访问了。

JAVA本地方法适用的情况 
1.为了使用底层的主机平台的某个特性,而这个特性不能通过JAVA API访问

2.为了访问一个老的系统或者使用一个已有的库,而这个系统或这个库不是用JAVA编写的

3.为了加快程序的性能,而将一段时间敏感的代码作为本地方法实现。

  native不能与abstract连用,因为native是有方法体的,只不过不是java语言实现的,而abstract表示没有方法体。

  如果一个含有本地方法的类被继承,子类会继承这个本地方法并且可以用java语言重写这个方法(这个似乎看起来有些奇怪),同样的如果一个本地方法被final标识,它被继承后不能被重写。(https://blog.csdn.net/wbl313/article/details/2560690)


  1. /**
  2. * Returns the runtime class of this {@code Object}. The returned
  3. * {@code Class} object is the object that is locked by {@code
  4. * static synchronized} methods of the represented class.
  5. *
  6. * <p><b>The actual result type is {@code Class<? extends |X|>}
  7. * where {@code |X|} is the erasure of the static type of the
  8. * expression on which {@code getClass} is called.</b> For
  9. * example, no cast is required in this code fragment:</p>
  10. *
  11. * <p>
  12. * {@code Number n = 0; }<br>
  13. * {@code Class<? extends Number> c = n.getClass(); }
  14. * </p>
  15. *
  16. * @return The {@code Class} object that represents the runtime
  17. * class of this object.
  18. * @jls 15.8.2 Class Literals
  19. */
  20. public final native Class<?> getClass();

  本地实现,不允许重写。返回运行时的class,由static synchronized方法锁定。

  1. package demo;
  2.  
  3. public class TestClass extends Aa {
  4.  
  5. public static void main(String[] args) {
  6. Aa a = new TestClass();
  7. a.test();
  8. System.out.println(a.getClass()); // class demo.TestClass
  9. System.out.println(a.getClass().getSuperclass()); // class demo.Aa
  10. System.out.println(a.toString()); // demo.TestClass@139a55
  11.  
  12. System.out.println("===========================");
  13.  
  14. TestClass test = new TestClass();
  15. test.test();
  16. System.out.println(test.getClass()); // class demo.TestClass
  17. System.out.println(test.getClass().getSuperclass()); // class demo.Aa
  18. System.out.println(test.toString()); // demo.TestClass@1db9742
  19. }
  20.  
  21. }
  22. class Aa{
  23. public void test(){
  24. System.out.println(this.getClass()); // class demo.TestClass
  25. System.out.println(super.getClass()); // class demo.TestClass
  26. System.out.println(this.getClass().getSuperclass()); // class demo.Aa
  27. System.out.println(super.getClass().getSuperclass()); // class demo.Aa
  28. System.out.println(this.toString()); // demo.TestClass@139a55
  29. System.out.println(super.toString()); // demo.TestClass@139a55
  30. }
  31. }
  32. /*
  33. class demo.TestClass
  34. class demo.TestClass
  35. class demo.Aa
  36. class demo.Aa
  37. demo.TestClass@139a55
  38. demo.TestClass@139a55
  39. class demo.TestClass
  40. class demo.Aa
  41. demo.TestClass@139a55
  42. ===========================
  43. class demo.TestClass
  44. class demo.TestClass
  45. class demo.Aa
  46. class demo.Aa
  47. demo.TestClass@1db9742
  48. demo.TestClass@1db9742
  49. class demo.TestClass
  50. class demo.Aa
  51. demo.TestClass@1db9742
  52. */

3.为什么this.getClass()和super.getClass()效果相同?

https://www.cnblogs.com/lcchuguo/p/4804990.html

  看了上篇给出的解释明白了,关键在于Object类中getClass()的定义:Returns the runtime class of this {@code Object}.规定返回对象的运行时类,即不管调用TestClass对象的this.getClass()还是super.getClass(),去调用的getClass()的对象是TestClass对象,super也是该TestClass对象的super,即TestClass对象.super.getClass(),处于最下面的依然是TestClass实例对象。所以不管是this还是super,它们对应的运行时类都是TestClass。

4. getClass(), .class区别

  1. package demo;
  2.  
  3. public class TestPrivate extends A{
  4.  
  5. public static void main(String[] args) {
  6. A obj = new TestPrivate();
  7. System.out.println(obj.getClass().getName());
  8. System.out.println(A.class);
  9. }
  10.  
  11. }
  12. class A{
  13. private int count;
  14. private void out(){
  15. System.out.println("A private method");
  16. }
  17. }
  18.  
  19. /*

obj.getClass().getName() 可以定位到Object和Class类中的代码处

A.class无法定位代码

*/

getClass() 利用这个方法就可以获得一个实例的类型类。类型类指的是代表一个类型的类,因为一切皆是对象,类型也不例外,在Java使用类型类来表示一个类型。所有的类型类都是Class类的实例

是一个类的实例所具备的方法,运行时才能确定(反射);

通过返回的Class对象获取Person的相关信息,比如:获取Person的构造方法,方法,属性有哪些等等信息(当我们想要获取Person的信息,比如:获取Person的名字,获取Person的构造函数,获取Person的继承关系等等这些Person的相关信息就不能仅仅只是通过new Person()的方式了。而是需要获取内存中实实在在存在的这个Class Person,通过获取到的。

Person p = new Person(1,”刘德华”); 
Class cla = p.getClass(); // 通过对象p调用getClass()方法返回Class

然后通过cla对象来获取Person的相关信息,因为Class提供了大量的方法来获取类(?extends Object)的信息)

.class 一个类方法,编译时确定

5.getClass()返回的是Class类的实例的理解

(https://blog.csdn.net/expect521/article/details/79139829)

同理对于Person类,或者准确的说每个类(除所有类的父类Object)也有两个称呼,既可以称为是类,也可称为变量。参照物不同称呼不同。

参照物: Person的属性id,name 则:Person的称呼是类(Class) 
参照物: Class类 则:Person的称呼是变量/属性

例如:

String name

Class Person

name的类型是String,此时 Class Person 的性质和String name一样。

String 等同于 Class,是类。

name 等同于 Person,是对象 / 变量的称呼。

String类下有很多方法供name对象使用,同理Class类下也有很多方法供Person对象使用。

Class类和String类一样,都是继承于Object类,Object是所有类的根类 。

6.Class类继承于Object类?

7.Why Object is Super Class in Java?

https://javapapers.com/java/why-object-is-super-class-in-java/

①By having the Object as the super class of all Java classes, without knowing the type we can pass around objects using the Object declaration.(通用--未知类型)

②Before generics was introduced, imagine the state of heterogeneous Java collections. A collection class like ArrayList allows to store any type of classes. It was made possible only by Object class hierarchy.(泛型之前--任何类型)

③The other reason would be to bring a common blueprint for all classes and have some list of functions same among them. I am referring to methods like hashCode(), clone(), toString() and methods for threading which is defined in Object class.(通用methods)

如下示例:

  1. package demo;
  2.  
  3. public class SuperClass {
  4.  
  5. public static void main(String[] args) {
  6. String str = "java";
  7. Class classstr = str.getClass();
  8. System.out.println("the super class of String is ----> " + classstr.getSuperclass());
  9. Object obj = new Object();
  10. Class classobj = obj.getClass();
  11. System.out.println("the super class of Object is ---> " + classobj.getSuperclass());
  12. Class c = classobj.getClass();
  13. System.out.println("the super class of Class is ---> " + c.getSuperclass());
  14. } // end main
  15.  
  16. } // end SuperClass
  17. /*
  18. the super class of String is ----> class java.lang.Object
  19. the super class of Object is ---> null
  20. the super class of Class is ---> class java.lang.Object
  21. */

  1. /**
  2. * Returns a hash code value for the object. This method is
  3. * supported for the benefit of hash tables such as those provided by
  4. * {@link java.util.HashMap}.
  5. * <p>
  6. * The general contract of {@code hashCode} is:
  7. * <ul>
  8. * <li>Whenever it is invoked on the same object more than once during
  9. * an execution of a Java application, the {@code hashCode} method
  10. * must consistently return the same integer, provided no information
  11. * used in {@code equals} comparisons on the object is modified.
  12. * This integer need not remain consistent from one execution of an
  13. * application to another execution of the same application.
  14. * <li>If two objects are equal according to the {@code equals(Object)}
  15. * method, then calling the {@code hashCode} method on each of
  16. * the two objects must produce the same integer result.
  17. * <li>It is <em>not</em> required that if two objects are unequal
  18. * according to the {@link java.lang.Object#equals(java.lang.Object)}
  19. * method, then calling the {@code hashCode} method on each of the
  20. * two objects must produce distinct integer results. However, the
  21. * programmer should be aware that producing distinct integer results
  22. * for unequal objects may improve the performance of hash tables.
  23. * </ul>
  24. * <p>
  25. * As much as is reasonably practical, the hashCode method defined by
  26. * class {@code Object} does return distinct integers for distinct
  27. * objects. (This is typically implemented by converting the internal
  28. * address of the object into an integer, but this implementation
  29. * technique is not required by the
  30. * Java&trade; programming language.)
  31. *
  32. * @return a hash code value for this object.
  33. * @see java.lang.Object#equals(java.lang.Object)
  34. * @see java.lang.System#identityHashCode
  35. */
  36. public native int hashCode();

https://blog.csdn.net/luanlouis/article/details/41547649

Java 中Object对象的hashcode()返回值一定不会是Object对象的内存地址这么简单!深挖源码

https://stackoverflow.com/questions/13860194/what-is-an-internal-address-in-java/13860488#13860488

从JDK7开始,Object.hashCode()返回的就不再是地址了。

注意this.hashCode()和this.getClass().hashCode()是不同的,见toString()处的测试。

  同一对象多次调用应该返回同一个Integer值;equals返回相等,hashCode也应该相等;equals不同,hashCode应该不同(不是必须)------>提升hash tables的性能。对于不同的对象返回不同的Integer。

  equals--true,hashCode--true(符合Object规范+hashSet等的规范);hashCode--true,equals不一定true;equals--false,hashCode不一定false。

  1. /**
  2. * Indicates whether some other object is "equal to" this one.
  3. * <p>
  4. * The {@code equals} method implements an equivalence relation
  5. * on non-null object references:
  6. * <ul>
  7. * <li>It is <i>reflexive</i>: for any non-null reference value
  8. * {@code x}, {@code x.equals(x)} should return
  9. * {@code true}.
  10. * <li>It is <i>symmetric</i>: for any non-null reference values
  11. * {@code x} and {@code y}, {@code x.equals(y)}
  12. * should return {@code true} if and only if
  13. * {@code y.equals(x)} returns {@code true}.
  14. * <li>It is <i>transitive</i>: for any non-null reference values
  15. * {@code x}, {@code y}, and {@code z}, if
  16. * {@code x.equals(y)} returns {@code true} and
  17. * {@code y.equals(z)} returns {@code true}, then
  18. * {@code x.equals(z)} should return {@code true}.
  19. * <li>It is <i>consistent</i>: for any non-null reference values
  20. * {@code x} and {@code y}, multiple invocations of
  21. * {@code x.equals(y)} consistently return {@code true}
  22. * or consistently return {@code false}, provided no
  23. * information used in {@code equals} comparisons on the
  24. * objects is modified.
  25. * <li>For any non-null reference value {@code x},
  26. * {@code x.equals(null)} should return {@code false}.
  27. * </ul>
  28. * <p>
  29. * The {@code equals} method for class {@code Object} implements
  30. * the most discriminating possible equivalence relation on objects;
  31. * that is, for any non-null reference values {@code x} and
  32. * {@code y}, this method returns {@code true} if and only
  33. * if {@code x} and {@code y} refer to the same object
  34. * ({@code x == y} has the value {@code true}).
  35. * <p>
  36. * Note that it is generally necessary to override the {@code hashCode}
  37. * method whenever this method is overridden, so as to maintain the
  38. * general contract for the {@code hashCode} method, which states
  39. * that equal objects must have equal hash codes.
  40. *
  41. * @param obj the reference object with which to compare.
  42. * @return {@code true} if this object is the same as the obj
  43. * argument; {@code false} otherwise.
  44. * @see #hashCode()
  45. * @see java.util.HashMap
  46. */
  47. public boolean equals(Object obj) {
  48. return (this == obj);
  49. }

  和non-null对象引用的等值判断。具有自反性、对称性、传递性和一致性。对于任何non-null引用x,x.equals(null)--false。大多数实现遵循规则:x.equals(y)--true,当且仅当x==y。需要重写,注意和hashCode方法之间的约束。

 8. 为什么equals和hashCode方法要定义在Object类中而不是单独的接口?

https://stackoverflow.com/questions/8113752/why-equals-and-hashcode-were-defined-in-object

(还不理解chaos到底指什么??)


  1. /**
  2. * Creates and returns a copy of this object. The precise meaning
  3. * of "copy" may depend on the class of the object. The general
  4. * intent is that, for any object {@code x}, the expression:
  5. * <blockquote>
  6. * <pre>
  7. * x.clone() != x</pre></blockquote>
  8. * will be true, and that the expression:
  9. * <blockquote>
  10. * <pre>
  11. * x.clone().getClass() == x.getClass()</pre></blockquote>
  12. * will be {@code true}, but these are not absolute requirements.
  13. * While it is typically the case that:
  14. * <blockquote>
  15. * <pre>
  16. * x.clone().equals(x)</pre></blockquote>
  17. * will be {@code true}, this is not an absolute requirement.
  18. * <p>
  19. * By convention, the returned object should be obtained by calling
  20. * {@code super.clone}. If a class and all of its superclasses (except
  21. * {@code Object}) obey this convention, it will be the case that
  22. * {@code x.clone().getClass() == x.getClass()}.
  23. * <p>
  24. * By convention, the object returned by this method should be independent
  25. * of this object (which is being cloned). To achieve this independence,
  26. * it may be necessary to modify one or more fields of the object returned
  27. * by {@code super.clone} before returning it. Typically, this means
  28. * copying any mutable objects that comprise the internal "deep structure"
  29. * of the object being cloned and replacing the references to these
  30. * objects with references to the copies. If a class contains only
  31. * primitive fields or references to immutable objects, then it is usually
  32. * the case that no fields in the object returned by {@code super.clone}
  33. * need to be modified.
  34. * <p>
  35. * The method {@code clone} for class {@code Object} performs a
  36. * specific cloning operation. First, if the class of this object does
  37. * not implement the interface {@code Cloneable}, then a
  38. * {@code CloneNotSupportedException} is thrown. Note that all arrays
  39. * are considered to implement the interface {@code Cloneable} and that
  40. * the return type of the {@code clone} method of an array type {@code T[]}
  41. * is {@code T[]} where T is any reference or primitive type.
  42. * Otherwise, this method creates a new instance of the class of this
  43. * object and initializes all its fields with exactly the contents of
  44. * the corresponding fields of this object, as if by assignment; the
  45. * contents of the fields are not themselves cloned. Thus, this method
  46. * performs a "shallow copy" of this object, not a "deep copy" operation.
  47. * <p>
  48. * The class {@code Object} does not itself implement the interface
  49. * {@code Cloneable}, so calling the {@code clone} method on an object
  50. * whose class is {@code Object} will result in throwing an
  51. * exception at run time.
  52. *
  53. * @return a clone of this instance.
  54. * @throws CloneNotSupportedException if the object's class does not
  55. * support the {@code Cloneable} interface. Subclasses
  56. * that override the {@code clone} method can also
  57. * throw this exception to indicate that an instance cannot
  58. * be cloned.
  59. * @see java.lang.Cloneable
  60. */
  61. protected native Object clone() throws CloneNotSupportedException;

  方法有protected修饰,所以子类实现需要覆盖此方法并实现Cloneable接口,才能在外部实现clone功能

重写

①被复制的类需要实现Cloneable接口(否则抛异常),该接口为标记接口,不含任何方法

②覆盖clone(),访问修饰符设为public。方法中调用super.clone()方法得到需要的复制对象

  创建并返回该对象的一个副本。副本精确的定义取决于该对象的副本。常x.clone() != x ----true,x.getClass() == x.clone().getClass() ---true(不是绝对的约束),通常有x.equals(x.clone()) --true(也不是绝对约束)。返回的副本应该有对应所有副本的引用(super.clone)----> x.getClass() == x.clone().getClass() ---true。

  返回的副本和调用的对象独立。

  在某些场景中,我们需要获取到一个对象的拷贝用于某些处理。这时候就可以用到Java中的Object.clone方法进行对象复制,得到一个一模一样的新对象。但是在实际使用过程中会发现:当对象中含有可变的引用类型属性时,在复制得到的新对象对该引用类型属性内容进行修改,原始对象响应的属性内容也会发生变化,这就是"浅拷贝"的现象。方法说明也表示该方法是“浅拷贝”(Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.)

9.关于创建对象的两种方式(new,clone),clone与引用复制,浅拷贝与深拷贝

https://blog.csdn.net/it_zkc/article/details/73733527

创建对象的两种方式:

①new 找new后面类的类型,按此类型分配内存,进行初始化(声明、初始化块、构造器),通过this返回新创建对象的引用

②clone 分配内存,大小与调用clone方法的对象一样,将调用对象的各个值赋给新创建对象

浅拷贝与深拷贝:


  1. /**
  2. * Returns a string representation of the object. In general, the
  3. * {@code toString} method returns a string that
  4. * "textually represents" this object. The result should
  5. * be a concise but informative representation that is easy for a
  6. * person to read.
  7. * It is recommended that all subclasses override this method.
  8. * <p>
  9. * The {@code toString} method for class {@code Object}
  10. * returns a string consisting of the name of the class of which the
  11. * object is an instance, the at-sign character `{@code @}', and
  12. * the unsigned hexadecimal representation of the hash code of the
  13. * object. In other words, this method returns a string equal to the
  14. * value of:
  15. * <blockquote>
  16. * <pre>
  17. * getClass().getName() + '@' + Integer.toHexString(hashCode())
  18. * </pre></blockquote>
  19. *
  20. * @return a string representation of the object.
  21. */
  22. public String toString() {
  23. return getClass().getName() + "@" + Integer.toHexString(hashCode());
  24. }

  之前在getClass()时看到this.toString()和super.toString()效果使一样的,都是返回了this对应的类的toString。

10.为什么this.toString()和super.toString()返回相同?

  看Object对toString()的默认实现,getClass()前有默认this调用,即第一步为this.getClass()返回了this运行时的类,即调用this和super的toString方法返回一样是因为这里的getClass(),它们都得到了运行时类,所以在“@”前面的应该相同,再看“@”后面的Integer.toHexString(hashCode()),我们看它们的hashCode()的测试

  1. package demo;
  2.  
  3. public class TestClass extends Aa {
  4.  
  5. public static void main(String[] args) {
  6. Aa a = new TestClass();
  7. System.out.println("++++++++++++++ a ++++++++++++");
  8. a.test();
  9. a.testSSuer();
  10. System.out.println("class--" + a.getClass().getName() + " hashCode--" + a.getClass().hashCode());
  11.  
  12. System.out.println("===========================");
  13.  
  14. Aa aa = new Aa();
  15. System.out.println("++++++++++++++++++++ aa ++++++++++++++++");
  16. aa.test();
  17. System.out.println("class--" + aa.getClass().getName() + " hashCode--" + aa.getClass().hashCode());
  18.  
  19. System.out.println("===========================");
  20.  
  21. TestClass test = new TestClass();
  22. System.out.println("++++++++++++++++ test ++++++++++++++");
  23. test.test();
  24. test.testSSuer();
  25. System.out.println("class--" + test.getClass().getName() + " hashCode--" + test.getClass().hashCode());
  26.  
  27. System.out.println("===========================");
  28.  
  29. TestClass test2 = new TestClass();
  30. System.out.println("+++++++++++++++++ test2 ++++++++++++");
  31. test2.test();
  32. test2.testSSuer();
  33. System.out.println("class--" + test2.getClass().getName() + " hashCode--" + test2.getClass().hashCode());
  34. }
  35.  
  36. }
  37. class Aa{
  38. private int count;
  39. private Object obj;
  40. // setter and getter methods
  41.  
  42. public int getCount() {
  43. return count;
  44. }
  45.  
  46. public void setCount(int count) {
  47. this.count = count;
  48. }
  49.  
  50. public Object getObj() {
  51. return obj;
  52. }
  53.  
  54. public void setObj(Object obj) {
  55. this.obj = obj;
  56. }
  57.  
  58. // test methods
  59.  
  60. public void test(){
  61. System.out.println(this.toString());
  62. System.out.println(super.toString());
  63. System.out.println(this.hashCode());
  64. System.out.println(super.hashCode());
  65. testSuper();
  66. }
  67.  
  68. private void testSuper() {
  69. System.out.println("************* super *************");
  70. System.out.println("class----" + this.getClass().getSuperclass().getName());
  71. System.out.println(this.getClass().getSuperclass().hashCode());
  72. System.out.println();
  73. }
  74. public void testSSuer(){
  75. System.out.println("+++++++++ SSuper ++++++++");
  76. System.out.println("class----" + this.getClass().getSuperclass().getSuperclass().getName());
  77. System.out.println(this.getClass().getSuperclass().getSuperclass().hashCode());
  78. System.out.println();
  79. }
  80. }
    /*

++++++++++++++ a ++++++++++++

demo.TestClass@139a55

demo.TestClass@139a55

1284693

1284693

*************  super  *************

class----demo.Aa

31168322

+++++++++ SSuper ++++++++

class----java.lang.Object

17225372

class--demo.TestClass hashCode--27134973

===========================

++++++++++++++++++++ aa ++++++++++++++++

demo.Aa@52e922

demo.Aa@52e922

5433634

5433634

*************  super  *************

class----java.lang.Object

17225372

class--demo.Aa hashCode--31168322

===========================

++++++++++++++++ test ++++++++++++++

demo.TestClass@25154f

demo.TestClass@25154f

2430287

2430287

*************  super  *************

class----demo.Aa

31168322

+++++++++ SSuper ++++++++

class----java.lang.Object

17225372

class--demo.TestClass hashCode--27134973

===========================

+++++++++++++++++ test2 ++++++++++++

demo.TestClass@10dea4e

demo.TestClass@10dea4e

17689166

17689166

*************  super  *************

class----demo.Aa

31168322

+++++++++ SSuper ++++++++

class----java.lang.Object

17225372

class--demo.TestClass hashCode--27134973

  1. */

  可以看到this和super的hashCode()返回值一样,但是通过this.getClass().hashCode()的返回值又和它们不同,且this.getClass().getSuperClass().hashCode()又和它们不一样,这是为什么呢?

  我们观察到一个现象:通过对象调用的hashCode()会返回不同的值,但是通过getClass().hashCode()会返回一致的结果,getClass()返回了对象的类,再通过类调用hashCode方法返回值是相同的,但是在Class类中并没有重写hashCode方法,所以Object中对对象的类的处理是不同的(运行在windows下),本地方法实现时做了区别对待?其实不是的,因为类Object、Aa、TestClass在Aa a = new TestClass();时就已经加载到内存中了,相当于一个类对象,即一个Class对象,在以后再new Object、Aa、TestClass时就不用再加载一次类了,所以通过getClass()方法返回了内存中加载的类,再在加载类中调用hashCode()返回的就是加载类相关的信息(包含了地址但不完全是地址)。

  现在又回到了那个问题上,为什么this.hashCode()和super.hashCode()返回一样?

  着手点:super关键字,继承的内存图

  为什么子类不能通过super来调用父类的private属性或方法?super和this能调用的属性和方法一样,除过super调用构造器及其在父类和子类中存在一样方法时调用父类方法,super还有什么用?

https://bbs.csdn.net/topics/390836899

从图中可知,压根没有父类对象,只有子类对象,而且this完全引用这个对象,super只是引用了这个对象中从父类继承来的成员,也就是说,除了super不能访问子类定义的成员之外,super和this是同一个对象。

我觉得是这样的,new子类对象时,先开辟一片内存空间,先给父类的成员变量安排好内存单元,然后子类自己的数据接着来分配给予内存单元,相当于父类数据与子类数据合租一个房子,房子是子类的。

一个对象可以理解为一个房子,而一个类只是规定了什么地方要放什么东西,比如客厅要放沙发,餐厅要有餐桌。
创建一个新对象,就是建造一栋新房子,如果你不去初始化对象,那么这个房子就是空的,没有任何装饰家具,你也不能用它来做任何有意义的事(当然这只是个比喻,空房子不能说没有用)。
当调用构造函数时,才会真正让这个对象有意义,那就是布置这个房子,布置这个房子有很多设计师,子类和父类就是两个设计师,他们之间的关系可以理解为父类设计师是子类设计师的指导,首先子类会让父类先来,父类说他要A B C D E等等,于是就叫人搬来这些东西放在房子里,父类布置好了,子类就来布置了,子类就会继续在房子里添置家具等等,有时候父类和子类会有冲突,比如父类说瓷砖地板好,子类说木地板好,这时候以子类为准,因为最终这个房子是给子类的,父类只是一个顾问指导而已,这就相当于方法重写。
所以如果你说创建一个子类对象会不会同时也创建了父类对象,那答案肯定是没有。
说有的如果他的意思是这个子类对象在某个时刻完全是一个父类对象,因为那个时刻他具备了父类对象所有的特征,但不具备子类的特征,那还是可以接受的,但这个过程只会创建一个对象,如果说有的认为创建了两个或者更多的对象,那肯定是错误的。

  

  因为Aa和TestClass类都没有重写hashCode函数,所以super和this都可以调用hashCode(),由于hashCode需要地址信息而this和super是一样的(一栋房子的地址),所以它们返回的hashCode()是相同的。即它们调用的toString()也是一样的。


查看Integer.toHexString()方法:

  1. public static String toHexString(int i) {
  2. return toUnsignedString0(i, 4);
  3. }
  1. /**
  2. * Convert the integer to an unsigned number.
  3. */
  4. private static String toUnsignedString0(int val, int shift) {
  5. // assert shift > 0 && shift <=5 : "Illegal shift value";
  6. int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
  7. int chars = Math.max(((mag + (shift - 1)) / shift), 1);
  8. char[] buf = new char[chars];
  9.  
  10. formatUnsignedInt(val, shift, buf, 0, chars);
  11.  
  12. // Use special constructor which takes over "buf".
  13. return new String(buf, true);
  14. }

Integer.SIZE = 32

  1. public static int numberOfLeadingZeros(int i) {
  2. // HD, Figure 5-6
  3. if (i == 0)
  4. return 32;
  5. int n = 1;
  6. if (i >>> 16 == 0) { n += 16; i <<= 16; }
  7. if (i >>> 24 == 0) { n += 8; i <<= 8; }
  8. if (i >>> 28 == 0) { n += 4; i <<= 4; }
  9. if (i >>> 30 == 0) { n += 2; i <<= 2; }
  10. n -= i >>> 31;
  11. return n;
  12. }
  1. /**
  2. * Format a long (treated as unsigned) into a character buffer.
  3. * @param val the unsigned int to format
  4. * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
  5. * @param buf the character buffer to write to
  6. * @param offset the offset in the destination buffer to start at
  7. * @param len the number of characters to write
  8. * @return the lowest character location used
  9. */
  10. static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
  11. int charPos = len;
  12. int radix = 1 << shift;
  13. int mask = radix - 1;
  14. do {
  15. buf[offset + --charPos] = Integer.digits[val & mask];
  16. val >>>= shift;
  17. } while (val != 0 && charPos > 0);
  18.  
  19. return charPos;
  20. }

  每四位和1111做&运算,根据digits对应的值赋值。(先从第四位开始)

  1. /**
  2. * All possible chars for representing a number as a String
  3. */
  4. final static char[] digits = {
  5. '0' , '1' , '2' , '3' , '4' , '5' ,
  6. '6' , '7' , '8' , '9' , 'a' , 'b' ,
  7. 'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
  8. 'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
  9. 'o' , 'p' , 'q' , 'r' , 's' , 't' ,
  10. 'u' , 'v' , 'w' , 'x' , 'y' , 'z'
  11. };

  1. /**
  2. * Wakes up a single thread that is waiting on this object's
  3. * monitor. If any threads are waiting on this object, one of them
  4. * is chosen to be awakened. The choice is arbitrary and occurs at
  5. * the discretion of the implementation. A thread waits on an object's
  6. * monitor by calling one of the {@code wait} methods.
  7. * <p>
  8. * The awakened thread will not be able to proceed until the current
  9. * thread relinquishes the lock on this object. The awakened thread will
  10. * compete in the usual manner with any other threads that might be
  11. * actively competing to synchronize on this object; for example, the
  12. * awakened thread enjoys no reliable privilege or disadvantage in being
  13. * the next thread to lock this object.
  14. * <p>
  15. * This method should only be called by a thread that is the owner
  16. * of this object's monitor. A thread becomes the owner of the
  17. * object's monitor in one of three ways:
  18. * <ul>
  19. * <li>By executing a synchronized instance method of that object.
  20. * <li>By executing the body of a {@code synchronized} statement
  21. * that synchronizes on the object.
  22. * <li>For objects of type {@code Class,} by executing a
  23. * synchronized static method of that class.
  24. * </ul>
  25. * <p>
  26. * Only one thread at a time can own an object's monitor.
  27. *
  28. * @throws IllegalMonitorStateException if the current thread is not
  29. * the owner of this object's monitor.
  30. * @see java.lang.Object#notifyAll()
  31. * @see java.lang.Object#wait()
  32. */
  33. public final native void notify();

  不能被重写。唤醒该对象monitor中等待的单线程。有多个线程则选择一个唤醒。在实现时选择是任意且灵活的。

  执行该方法的线程唤醒在对象的等待池中等待的一个线程,JVM从对象的等待池中随机选择一个线程,把它转到对象的锁池中。该方法的调用,会从所有正在等待obj对象锁的线程中,唤醒其中的一个(选择算法依赖于不同实现),被唤醒的线程此时加入到了obj对象锁的争夺之中,然而该notify方法的执行线程此时并未释放obj的对象锁,而是离开synchronized代码块时释放。因此在notify方法之后,synchronized代码块结束之前,所有其他被唤醒的,等待obj对象锁的线程依旧被阻塞https://my.oschina.net/fengheju/blog/169695)

https://blog.csdn.net/vk5176891/article/details/53945677

三个方法都必须在synchronized 同步关键字所限定的作用域中调用,否则会报错java.lang.IllegalMonitorStateException ,意思是因为没有同步,所以线程对对象锁的状态是不确定的,不能调用这些方法。

wait 表示持有对象锁的线程A准备释放对象锁权限,释放cpu资源并进入等待。

notify 表示持有对象锁的线程A准备释放对象锁权限,通知jvm唤醒某个竞争该对象锁的线程X。线程A synchronized 代码作用域结束后,线程X直接获得对象锁权限,其他竞争线程继续等待(即使线程X同步完毕,释放对象锁,其他竞争线程仍然等待,直至有新的notify ,notifyAll被调用)。

notifyAll 表示持有对象锁的线程A准备释放对象锁权限,通知jvm唤醒所有竞争该对象锁的线程,线程A synchronized 代码作用域结束后,jvm通过算法将对象锁权限指派给某个线程X,所有被唤醒的线程不再等待。线程X synchronized 代码作用域结束后,之前所有被唤醒的线程都有可能获得该对象锁权限,这个由JVM算法决定。

wait有三个重载方法,同时必须捕获非运行时异常InterruptedException。

wait() 进入等待,需要notify ,notifyAll才能唤醒

wait(long timeout) 进入等待,经过timeout 超时后,若未被唤醒,则自动唤醒

wait(timeout, nanos) 进入等待,经过timeout 超时后,若未被唤醒,则自动唤醒。相对wait(long timeout) 更加精确时间。

  

  为何这三个不是Thread类声明中的方法,而是Object类中声明的方法https://www.cnblogs.com/csuwater/p/5411693.html

  为何这三个不是Thread类声明中的方法,而是Object类中声明的方法(当然由于Thread类继承了Object类,所以Thread也可以调用者三个方法)?其实这个问题很简单,由于每个对象都拥有monitor(即锁),所以让当前线程等待某个对象的锁,当然应该通过这个对象来操作了。而不是用当前线程来操作,因为当前线程可能会等待多个线程的锁,如果通过线程来操作,就非常复杂了。

  1. /**
  2. * Wakes up all threads that are waiting on this object's monitor. A
  3. * thread waits on an object's monitor by calling one of the
  4. * {@code wait} methods.
  5. * <p>
  6. * The awakened threads will not be able to proceed until the current
  7. * thread relinquishes the lock on this object. The awakened threads
  8. * will compete in the usual manner with any other threads that might
  9. * be actively competing to synchronize on this object; for example,
  10. * the awakened threads enjoy no reliable privilege or disadvantage in
  11. * being the next thread to lock this object.
  12. * <p>
  13. * This method should only be called by a thread that is the owner
  14. * of this object's monitor. See the {@code notify} method for a
  15. * description of the ways in which a thread can become the owner of
  16. * a monitor.
  17. *
  18. * @throws IllegalMonitorStateException if the current thread is not
  19. * the owner of this object's monitor.
  20. * @see java.lang.Object#notify()
  21. * @see java.lang.Object#wait()
  22. */
  23. public final native void notifyAll();

  唤醒该对象monitor中的所有线程

  1. /**
  2. * Causes the current thread to wait until either another thread invokes the
  3. * {@link java.lang.Object#notify()} method or the
  4. * {@link java.lang.Object#notifyAll()} method for this object, or a
  5. * specified amount of time has elapsed.
  6. * <p>
  7. * The current thread must own this object's monitor.
  8. * <p>
  9. * This method causes the current thread (call it <var>T</var>) to
  10. * place itself in the wait set for this object and then to relinquish
  11. * any and all synchronization claims on this object. Thread <var>T</var>
  12. * becomes disabled for thread scheduling purposes and lies dormant
  13. * until one of four things happens:
  14. * <ul>
  15. * <li>Some other thread invokes the {@code notify} method for this
  16. * object and thread <var>T</var> happens to be arbitrarily chosen as
  17. * the thread to be awakened.
  18. * <li>Some other thread invokes the {@code notifyAll} method for this
  19. * object.
  20. * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
  21. * thread <var>T</var>.
  22. * <li>The specified amount of real time has elapsed, more or less. If
  23. * {@code timeout} is zero, however, then real time is not taken into
  24. * consideration and the thread simply waits until notified.
  25. * </ul>
  26. * The thread <var>T</var> is then removed from the wait set for this
  27. * object and re-enabled for thread scheduling. It then competes in the
  28. * usual manner with other threads for the right to synchronize on the
  29. * object; once it has gained control of the object, all its
  30. * synchronization claims on the object are restored to the status quo
  31. * ante - that is, to the situation as of the time that the {@code wait}
  32. * method was invoked. Thread <var>T</var> then returns from the
  33. * invocation of the {@code wait} method. Thus, on return from the
  34. * {@code wait} method, the synchronization state of the object and of
  35. * thread {@code T} is exactly as it was when the {@code wait} method
  36. * was invoked.
  37. * <p>
  38. * A thread can also wake up without being notified, interrupted, or
  39. * timing out, a so-called <i>spurious wakeup</i>. While this will rarely
  40. * occur in practice, applications must guard against it by testing for
  41. * the condition that should have caused the thread to be awakened, and
  42. * continuing to wait if the condition is not satisfied. In other words,
  43. * waits should always occur in loops, like this one:
  44. * <pre>
  45. * synchronized (obj) {
  46. * while (&lt;condition does not hold&gt;)
  47. * obj.wait(timeout);
  48. * ... // Perform action appropriate to condition
  49. * }
  50. * </pre>
  51. * (For more information on this topic, see Section 3.2.3 in Doug Lea's
  52. * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
  53. * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
  54. * Language Guide" (Addison-Wesley, 2001).
  55. *
  56. * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
  57. * interrupted} by any thread before or while it is waiting, then an
  58. * {@code InterruptedException} is thrown. This exception is not
  59. * thrown until the lock status of this object has been restored as
  60. * described above.
  61. *
  62. * <p>
  63. * Note that the {@code wait} method, as it places the current thread
  64. * into the wait set for this object, unlocks only this object; any
  65. * other objects on which the current thread may be synchronized remain
  66. * locked while the thread waits.
  67. * <p>
  68. * This method should only be called by a thread that is the owner
  69. * of this object's monitor. See the {@code notify} method for a
  70. * description of the ways in which a thread can become the owner of
  71. * a monitor.
  72. *
  73. * @param timeout the maximum time to wait in milliseconds.
  74. * @throws IllegalArgumentException if the value of timeout is
  75. * negative.
  76. * @throws IllegalMonitorStateException if the current thread is not
  77. * the owner of the object's monitor.
  78. * @throws InterruptedException if any thread interrupted the
  79. * current thread before or while the current thread
  80. * was waiting for a notification. The <i>interrupted
  81. * status</i> of the current thread is cleared when
  82. * this exception is thrown.
  83. * @see java.lang.Object#notify()
  84. * @see java.lang.Object#notifyAll()
  85. */
  86. public final native void wait(long timeout) throws InterruptedException;

  

  执行了该方法的线程释放对象的锁,JVM会把该线程放到对象的等待池中。该线程等待其它线程唤醒。该方法的调用,使得调用该方法的执行线程(T1)放弃obj的对象锁并阻塞,直到别的线程调用了obj的notifyAll方法、或者别的线程调用了obj的notify方法且JVM选择唤醒(T1),被唤醒的线程(T1)依旧阻塞在wait方法中,与其它的线程一起争夺obj的对象锁,直到它再次获得了obj的对象锁之后,才能从wait方法中返回。(除了notify方法,wait还有带有时间参数的版本,在等待了超过所设时间之后,T1线程一样会被唤醒,进入到争夺obj对象锁的行列;另外中断可以直接跳出wait方法)(https://my.oschina.net/fengheju/blog/169695)

  1. /**
  2. * Causes the current thread to wait until another thread invokes the
  3. * {@link java.lang.Object#notify()} method or the
  4. * {@link java.lang.Object#notifyAll()} method for this object, or
  5. * some other thread interrupts the current thread, or a certain
  6. * amount of real time has elapsed.
  7. * <p>
  8. * This method is similar to the {@code wait} method of one
  9. * argument, but it allows finer control over the amount of time to
  10. * wait for a notification before giving up. The amount of real time,
  11. * measured in nanoseconds, is given by:
  12. * <blockquote>
  13. * <pre>
  14. * 1000000*timeout+nanos</pre></blockquote>
  15. * <p>
  16. * In all other respects, this method does the same thing as the
  17. * method {@link #wait(long)} of one argument. In particular,
  18. * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
  19. * <p>
  20. * The current thread must own this object's monitor. The thread
  21. * releases ownership of this monitor and waits until either of the
  22. * following two conditions has occurred:
  23. * <ul>
  24. * <li>Another thread notifies threads waiting on this object's monitor
  25. * to wake up either through a call to the {@code notify} method
  26. * or the {@code notifyAll} method.
  27. * <li>The timeout period, specified by {@code timeout}
  28. * milliseconds plus {@code nanos} nanoseconds arguments, has
  29. * elapsed.
  30. * </ul>
  31. * <p>
  32. * The thread then waits until it can re-obtain ownership of the
  33. * monitor and resumes execution.
  34. * <p>
  35. * As in the one argument version, interrupts and spurious wakeups are
  36. * possible, and this method should always be used in a loop:
  37. * <pre>
  38. * synchronized (obj) {
  39. * while (&lt;condition does not hold&gt;)
  40. * obj.wait(timeout, nanos);
  41. * ... // Perform action appropriate to condition
  42. * }
  43. * </pre>
  44. * This method should only be called by a thread that is the owner
  45. * of this object's monitor. See the {@code notify} method for a
  46. * description of the ways in which a thread can become the owner of
  47. * a monitor.
  48. *
  49. * @param timeout the maximum time to wait in milliseconds.
  50. * @param nanos additional time, in nanoseconds range
  51. * 0-999999.
  52. * @throws IllegalArgumentException if the value of timeout is
  53. * negative or the value of nanos is
  54. * not in the range 0-999999.
  55. * @throws IllegalMonitorStateException if the current thread is not
  56. * the owner of this object's monitor.
  57. * @throws InterruptedException if any thread interrupted the
  58. * current thread before or while the current thread
  59. * was waiting for a notification. The <i>interrupted
  60. * status</i> of the current thread is cleared when
  61. * this exception is thrown.
  62. */
  63. public final void wait(long timeout, int nanos) throws InterruptedException {
  64. if (timeout < 0) {
  65. throw new IllegalArgumentException("timeout value is negative");
  66. }
  67.  
  68. if (nanos < 0 || nanos > 999999) {
  69. throw new IllegalArgumentException(
  70. "nanosecond timeout value out of range");
  71. }
  72.  
  73. if (nanos > 0) {
  74. timeout++;
  75. }
  76.  
  77. wait(timeout);
  78. }

源码直接简单加1??

https://www.zhihu.com/question/41808470/answer/137420141

主要点在于知道 timeout的单位为毫秒, 参数nanos 的单位为纳秒, 1毫秒 = 1000 微秒 = 1000 000 纳秒
处理时,由于纳秒级时间太短(我猜测), 所以对参数nanos 其采取了近似处理,即大于半毫秒的加1毫秒,小于1毫秒则舍弃(特殊情况下,参数timeout为0时,参数nanos大于0时,也算为1毫秒)

其主要作用应该在能更精确控制等待时间(尤其在高并发时,毫秒的时间节省也是很值得的)

  1. /**
  2. * Causes the current thread to wait until another thread invokes the
  3. * {@link java.lang.Object#notify()} method or the
  4. * {@link java.lang.Object#notifyAll()} method for this object.
  5. * In other words, this method behaves exactly as if it simply
  6. * performs the call {@code wait(0)}.
  7. * <p>
  8. * The current thread must own this object's monitor. The thread
  9. * releases ownership of this monitor and waits until another thread
  10. * notifies threads waiting on this object's monitor to wake up
  11. * either through a call to the {@code notify} method or the
  12. * {@code notifyAll} method. The thread then waits until it can
  13. * re-obtain ownership of the monitor and resumes execution.
  14. * <p>
  15. * As in the one argument version, interrupts and spurious wakeups are
  16. * possible, and this method should always be used in a loop:
  17. * <pre>
  18. * synchronized (obj) {
  19. * while (&lt;condition does not hold&gt;)
  20. * obj.wait();
  21. * ... // Perform action appropriate to condition
  22. * }
  23. * </pre>
  24. * This method should only be called by a thread that is the owner
  25. * of this object's monitor. See the {@code notify} method for a
  26. * description of the ways in which a thread can become the owner of
  27. * a monitor.
  28. *
  29. * @throws IllegalMonitorStateException if the current thread is not
  30. * the owner of the object's monitor.
  31. * @throws InterruptedException if any thread interrupted the
  32. * current thread before or while the current thread
  33. * was waiting for a notification. The <i>interrupted
  34. * status</i> of the current thread is cleared when
  35. * this exception is thrown.
  36. * @see java.lang.Object#notify()
  37. * @see java.lang.Object#notifyAll()
  38. */
  39. public final void wait() throws InterruptedException {
  40. wait(0);
  41. }

  1. /**
  1. * Called by the garbage collector on an object when garbage collection
  2. * determines that there are no more references to the object.
  3. * A subclass overrides the {@code finalize} method to dispose of
  4. * system resources or to perform other cleanup.
  5. * <p>
  6. * The general contract of {@code finalize} is that it is invoked
  7. * if and when the Java&trade; virtual
  8. * machine has determined that there is no longer any
  9. * means by which this object can be accessed by any thread that has
  10. * not yet died, except as a result of an action taken by the
  11. * finalization of some other object or class which is ready to be
  12. * finalized. The {@code finalize} method may take any action, including
  13. * making this object available again to other threads; the usual purpose
  14. * of {@code finalize}, however, is to perform cleanup actions before
  15. * the object is irrevocably discarded. For example, the finalize method
  16. * for an object that represents an input/output connection might perform
  17. * explicit I/O transactions to break the connection before the object is
  18. * permanently discarded.
  19. * <p>
  20. * The {@code finalize} method of class {@code Object} performs no
  21. * special action; it simply returns normally. Subclasses of
  22. * {@code Object} may override this definition.
  23. * <p>
  24. * The Java programming language does not guarantee which thread will
  25. * invoke the {@code finalize} method for any given object. It is
  26. * guaranteed, however, that the thread that invokes finalize will not
  27. * be holding any user-visible synchronization locks when finalize is
  28. * invoked. If an uncaught exception is thrown by the finalize method,
  29. * the exception is ignored and finalization of that object terminates.
  30. * <p>
  31. * After the {@code finalize} method has been invoked for an object, no
  32. * further action is taken until the Java virtual machine has again
  33. * determined that there is no longer any means by which this object can
  34. * be accessed by any thread that has not yet died, including possible
  35. * actions by other objects or classes which are ready to be finalized,
  36. * at which point the object may be discarded.
  37. * <p>
  38. * The {@code finalize} method is never invoked more than once by a Java
  39. * virtual machine for any given object.
  40. * <p>
  41. * Any exception thrown by the {@code finalize} method causes
  42. * the finalization of this object to be halted, but is otherwise
  43. * ignored.
  44. *
  45. * @throws Throwable the {@code Exception} raised by this method
  46. * @see java.lang.ref.WeakReference
  47. * @see java.lang.ref.PhantomReference
  48. * @jls 12.6 Finalization of Class Instances
  49. */
  50. protected void finalize() throws Throwable { }

  空方法且可以抛出任何异常。子类重写。

  这是GC清理对象之前所调用的清理方法,是回调方法,我们可以覆盖这个方法写一些清理的代码,GC会自动扫描没有引用的对象,即对象赋值为null;可以通过调用System.runFinalization()或System.runFinalizersOnExit()强制GC清理该对象前调用finalize()方法,GC有时不会调用对象的finalize()方法(由JVM决定)

访问垃圾收集在对象上当垃圾收集这确定这个对象上没有更多的引用时可能会触发finalize方法

一个子类重写了finalize方法处理系统资源或者执行其它的清理也就是调用System.gc可能会触发

这个一般的合约规定finalize,如果Java虚拟机已经确定这不再有任何意味这个对象能通过任何一个尚未死亡的线程访问的方法调用,除非是由于最后确定的其它对象或类的准备工作所采取的行动

finalize方法可以采取任何行动,包括使此对象再次可用于其它线程,finalize的通常是在对象不可撤销地丢弃之前执行清楚动作.例如:表示输入输出连接的对象的finalize方法可能会在对象被永久丢弃之前执行显式I/O事务来中断连接
Object中finalize操作只是返回一个正常线程

Java规范确保调用finalize的线程在调用finalize方法时不会持有任何用户可见的同步锁

如果finalize方法抛出未捕获的异常,则会忽略该异常,并终止该对象的定类。

finalize方法不会被任何对象调用多次

finalize方法抛出的任何异常都会导致该对象的终止被停止,否则就忽略

  调用对象,new对象,非new对象?(只负责回收堆内存中对象);是否与C++中的析构函数相同?(不同,析构函数一定会执行--释放回收,但finalize函数不一定会执行);finalize的其他用途?(判断对象在清理时是否安全释放)https://www.jianshu.com/p/e1b2db7bafce

JDK8下Object类源码理解的更多相关文章

  1. Thread类源码剖析

    目录 1.引子 2.JVM线程状态 3.Thread常用方法 4.拓展点 一.引子 说来也有些汗颜,搞了几年java,忽然发现竟然没拜读过java.lang.Thread类源码,这次特地拿出来晒一晒. ...

  2. Java集合---Array类源码解析

    Java集合---Array类源码解析              ---转自:牛奶.不加糖 一.Arrays.sort()数组排序 Java Arrays中提供了对所有类型的排序.其中主要分为Prim ...

  3. Java集合---Arrays类源码解析

    一.Arrays.sort()数组排序 Java Arrays中提供了对所有类型的排序.其中主要分为Primitive(8种基本类型)和Object两大类. 基本类型:采用调优的快速排序: 对象类型: ...

  4. Cocos2d-X3.0 刨根问底(六)----- 调度器Scheduler类源码分析

    上一章,我们分析Node类的源码,在Node类里面耦合了一个 Scheduler 类的对象,这章我们就来剖析Cocos2d-x的调度器 Scheduler 类的源码,从源码中去了解它的实现与应用方法. ...

  5. Caffe源码理解2:SyncedMemory CPU和GPU间的数据同步

    目录 写在前面 成员变量的含义及作用 构造与析构 内存同步管理 参考 博客:blog.shinelee.me | 博客园 | CSDN 写在前面 在Caffe源码理解1中介绍了Blob类,其中的数据成 ...

  6. Java并发编程笔记之Unsafe类和LockSupport类源码分析

    一.Unsafe类的源码分析 JDK的rt.jar包中的Unsafe类提供了硬件级别的原子操作,Unsafe里面的方法都是native方法,通过使用JNI的方式来访问本地C++实现库. rt.jar ...

  7. 基于SpringBoot的Environment源码理解实现分散配置

    前提 org.springframework.core.env.Environment是当前应用运行环境的公开接口,主要包括应用程序运行环境的两个关键方面:配置文件(profiles)和属性.Envi ...

  8. .NET Core 3.0之深入源码理解Startup的注册及运行

    原文:.NET Core 3.0之深入源码理解Startup的注册及运行   写在前面 开发.NET Core应用,直接映入眼帘的就是Startup类和Program类,它们是.NET Core应用程 ...

  9. 深入源码理解Spring整合MyBatis原理

    写在前面 聊一聊MyBatis的核心概念.Spring相关的核心内容,主要结合源码理解Spring是如何整合MyBatis的.(结合右侧目录了解吧) MyBatis相关核心概念粗略回顾 SqlSess ...

随机推荐

  1. Query a JSON array in SQL

    sql 中存的json 为数组: [{"Level":1,"Memo":"新用户"},{"Level":2," ...

  2. Vue系列之 => webpack处理样式文件

    处理css文件 安装 npm i style-loader css-loader -D main.js import $ from 'jquery' //Es6中导入模块的方式 import './c ...

  3. python安装pip的步骤记录

    因为重新装了系统,所以python所有的环境都要重新走一遍. 首先去python官网下载python最新版本.如果python没有自动加入环境变量的话就需要你自己手动加入.这个一般在安装python的 ...

  4. sql server导出数据,远程连接失败,需要设置权限

    在sql  server management中右键当前连接——>方面 在 服务器配置中 将  RemoteAccessEnabled.RemoteDacEnabled设置为TRUE 安全性—— ...

  5. JDK8到JDK12各个版本的重要特性整理

    JDK8新特性 1.Lambda表达式 2.函数式编程 3.接口可以添加默认方法和静态方法,也就是定义不需要实现类实现的方法 4.方法引用 5.重复注解,同一个注解可以使用多次 6.引入Optiona ...

  6. 关于用IIS在.net平台发布网页的一些坑

    说明:由于需要显示页面的表格的内容,要用pageOffice插件,而装pageoffice之前需要装.net3.5,直接导入. 为什么要分别装.net4.5和.net3.5 ? 都要装?  问题:刚才 ...

  7. Hadoop2-HDFS学习笔记之入门(不含YARN及MR的调度功能)

    架构 Hadoop整体由HDFS.YARN.MapReduce三大部分组成,推荐架构参考:https://www.cnblogs.com/zhjh256/p/10573684.html. 注:2.x的 ...

  8. 大量的rcuob进程

    环境: OS:Centos 7 问题,今天采购了一台dell R430机器,启动发现大量的如下进程[root@localhost opt]# toptop - 02:07:57 up 6:39, 2 ...

  9. 【Alpha】Scrum Meeting 8

    目录 前言 任务分配 燃尽图 会议照片 签入记录 困难 前言 第8次会议在4月12日21:00进行微信会议. 交流确认了任务进度,对下一阶段任务进行分配.时长15min. 任务分配 姓名 当前阶段任务 ...

  10. HDU 5919 Sequence II(主席树)题解

    题意:有A1 ~ An组成的数组,给你l r,L = min((l + ans[i - 1]) % n + 1, (r + ans[i - 1]) % n + 1),R = max((l + ans[ ...