为什么通过 "super" 和 "this" 调用 hashCode() 会给出相同的结果?
Why does hashCode() give the same result when called via "super" and "this"?
我知道 super 是一个引用变量,用于引用直接父对象 class 对象。但我发现 super
和 this
的哈希码相同,这意味着它们引用子对象。
那么,super
如何调用父class对象呢?
示例代码:
class Animal{
int a;
Animal(){
System.out.println("animal constructor ");
}
}
class Dog extends Animal{
int b;
Dog(){
System.out.println("dog constructyor ");
System.out.println(this.hashCode()+" "+super.hashCode());
System.out.println(this.getClass()+" "+super.getClass());
}
}
public class Super1{
public static void main(String[] args){
Dog d=new Dog();
System.out.println(d);
}
}
还有 classsuper 和 this 的 es 是一样的。
which means they refer to child object than how "super" is used to
invoke parent class object
和
Also classes of both the super and this are same.
我认为您不了解继承的工作原理。
当您实例化一个 subclass 时,它依赖于 super class 来创建它 (super()
) 但它不会创建两个对象。
仅创建子实例class。
而您在输出中获得的结果。
附带说明一下,如果您在子 class 中覆盖了 hashCode()
,调用
super.hashCode()
和 hashCode()
可以 return 不同的结果,因为第一个会调用父方法,第二个会调用被覆盖的方法。
I know that super is a reference variable which is used to refer immediate parent class object.
不,不是。它用于引用父 class 成员 。没有 'parent class object' 这样的东西。
But I find the hashcode of both super and this are same which means they refer to child object.
不,不是。
因为您没有在任何一个 class 中覆盖 hashCode()
,所以当您调用它时,无论您使用哪个引用调用它,您总是会得到相同的结果。
并且当您调用 super.getClass()
时,对象的 class 不会神奇地改变。
我知道 super 是一个引用变量,用于引用直接父对象 class 对象。但我发现 super
和 this
的哈希码相同,这意味着它们引用子对象。
那么,super
如何调用父class对象呢?
示例代码:
class Animal{
int a;
Animal(){
System.out.println("animal constructor ");
}
}
class Dog extends Animal{
int b;
Dog(){
System.out.println("dog constructyor ");
System.out.println(this.hashCode()+" "+super.hashCode());
System.out.println(this.getClass()+" "+super.getClass());
}
}
public class Super1{
public static void main(String[] args){
Dog d=new Dog();
System.out.println(d);
}
}
还有 classsuper 和 this 的 es 是一样的。
which means they refer to child object than how "super" is used to invoke parent class object
和
Also classes of both the super and this are same.
我认为您不了解继承的工作原理。
当您实例化一个 subclass 时,它依赖于 super class 来创建它 (super()
) 但它不会创建两个对象。
仅创建子实例class。
而您在输出中获得的结果。
附带说明一下,如果您在子 class 中覆盖了 hashCode()
,调用
super.hashCode()
和 hashCode()
可以 return 不同的结果,因为第一个会调用父方法,第二个会调用被覆盖的方法。
I know that super is a reference variable which is used to refer immediate parent class object.
不,不是。它用于引用父 class 成员 。没有 'parent class object' 这样的东西。
But I find the hashcode of both super and this are same which means they refer to child object.
不,不是。
因为您没有在任何一个 class 中覆盖 hashCode()
,所以当您调用它时,无论您使用哪个引用调用它,您总是会得到相同的结果。
并且当您调用 super.getClass()
时,对象的 class 不会神奇地改变。