作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
请帮助我理解继承是如何工作的。
如果我有两个类(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/
我是一名优秀的程序员,十分优秀!