java继承试图理解它是如何工作的
我有两门课:
public class A
{
protected int _x;
public A(){
_x = 1;
}
public A(int x) {
_x = x;
}
public void f(int x) {
_x += x;
}
public String toString() {
return "" + _x;
}
}
public class B extends A
{
public B() {
super(3);
}
public B(int x) {
super.f(x);
f(x);
}
public void f(int x)
{
_x -= x;
super.f(x);
}
}
主要内容:
public static void main(String [] args)
{
A[] arr = new A[3];
arr[0] = new B();
arr[1] = new A();
arr[2] = new B(5);
for(int i=0; i<arr.length; i++)
{
arr[i].f(2);
System.out.print(arr[i] + " ");
}
}
我试图理解为什么第一次打印后的结果是3
而不是1
开始时Class A
空构造函数被称为_x = 1
而不是f(int x) from class B
所谓的_x = _x - 2
所谓的_x = -1
和之后的Super.f(x)
{
# 1 楼答案
arr
数组中的第二个元素是A
类型的对象,它是用无参数构造函数初始化的你在那个对象上调用
f(2)
。这将是A#f(int)
方法(即A
类中的f()
方法)因此,将2与1相加,即3
看来你指的是第一个元素。第一个元素用no arg
B
构造函数初始化它调用
A
构造函数将
_x
设置为3
。在这个对象上调用f(2)
时,由于多态性和后期绑定,它会调用B
中的f(int)
方法这将删除2到3,即1。但是
super.f(x)
将调用A
版本的f(int)
将2添加回_x
,即_x
的最终结果是3