gpt4 book ai didi

java - 继承到底是如何运作的?

转载 作者:行者123 更新时间:2023-12-01 06:32:14 24 4
gpt4 key购买 nike

请帮助我理解继承是如何工作的。

如果我有两个类(class),家长和 child 。当我创建子实例时,父类实例是否也被构造?

我的Parent类的代码。

public class Parent {
private char s;

@Override
public int hashCode() {
return s;
}
}

child

public class Child extends Parent {
private int i;

public Child(int i) {
super();
this.i = i;
}

@Override
public int hashCode() {
return i;
}
}

最后是测试

public class Main {
public static void main(String[] args) {
Child child = new Child(100);
System.out.println(child.hashCode());
System.out.println(child.getClass().getSuperclass().hashCode());
}
}

在输出中我得到

100
2000502626

所以对象的哈希值是不同的。这意味着当我创建 Child 实例时,它也会创建 Parent 实例。我说得对吗?

最佳答案

您的问题与继承无关。

如您所料,您从 child 实例的 hashcode() 方法获得的 100

2000502626 来自 Parent.class,而不是 Parent 对象

Parent.class 的类型为 java.lang.Class

父对象具有类型Parent

关于java - 继承到底是如何运作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25445952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com