Java:将对象扩展到另一个对象

SmR*_*Guy 2 java oop inheritance

例如我有这个:

class A{
    private int mine = 0; //Some field...
    public A(int a){mine+=a; /*Some operation1...*/}
}


class B extends A{
    private int mine = 0; //Some field...
    public B(int a){mine-=a; /*Some operation2...*/}
}
Run Code Online (Sandbox Code Playgroud)

我得到:

error: constructor A in class A cannot be applied to given types;
    public B(int a){}
    required: int
    found: no arguments
    reason: actual and formal argument lists differ in length
    1 errors
Run Code Online (Sandbox Code Playgroud)

我不明白这个错误?什么告诉我做什么?

但是,如果"A"的构造函数没有参数,则代码可以工作.
但我需要做Operation1(aka mine+=a;),所以我需要A的参数,但后来我失败了.

我在这个神奇的圈子里关闭了.我该怎么办?

JB *_*zet 9

每个构造函数的第一条指令总是调用它的一个超类构造函数.如果您没有明确地执行此操作,编译器会为您插入此实例.构造函数

 public B(int a) {
     mine-=a; 
     /*Some operation2...*/
 }
Run Code Online (Sandbox Code Playgroud)

因此相当于

public B(int a) {
    super(); // invoke the no-arg super constructor
    mine-=a; 
    /*Some operation2...*/
}
Run Code Online (Sandbox Code Playgroud)

由于A没有no-arg构造函数,因此编译失败.在这种情况下,您必须明确地调用其中一个超级构造函数:

public B(int a) {
    super(a);
    mine-=a; 
    /*Some operation2...*/
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*rdt 7

每个构造函数都必须调用超类构造函数作为它的第一件事.如果你没有显式地通过它super(),编译器将隐式调用超类中的no-arts构造函数.但在你的情况下,超类没有no-args构造函数,此时编译器放弃了.

顺便说一下,在子类中重新声明一个字段通常是一个非常糟糕的主意,因为它会隐藏超类字段,但仍然会有两个字段.