我知道super是一个引用变量,用于引用直接父类对象。但是我发现super
和this
的哈希码都是相同的,这意味着它们引用了子对象。
然后,super
如何用来调用父类对象?
示例代码:
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);
}
}
此外,super和this的类都是相同的。
答案 0 :(得分:3)
我知道super是一个引用变量,用于引用直接父类对象。
不,不是。它用于引用父类成员。没有“父类对象”这样的东西。
但是我发现super和hash的哈希码都是相同的,这意味着它们引用了子对象。
不,它没有。
由于您没有覆盖其中任何一个类中的hashCode()
,因此当您调用它时,无论您使用哪个引用,都会得到相同的结果。
当你致电super.getClass()
时,对象的类别并没有神奇地改变。
答案 1 :(得分:1)
which means they refer to child object than how "super" is used to invoke parent class object
and
Also classes of both the super and this are same.
I think that you don't get how the inheritancy works.
When you instantiate a subclass, it relies on the super class to create it (super()
) but it doesn't create two objects.
Only an instance of the subclass is created.
Whereas the results that you get in your output.
As a side note, if you had overriden hashCode()
in the subclass, invoking
super.hashCode()
and hashCode()
could return a distinct result as the first one would invoke the parent method and the second one would invoke the overriden one.