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

标签 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...*/}
}

我得到:

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

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

不过,如果“A”的构造函数没有参数,则代码可以工作。
但是我需要执行操作1(又名mine+=a;),所以我需要A的参数,但后来我失败了。

我被封闭在这个魔法圈里了。我该怎么办?

最佳答案

每个构造函数的第一条指令始终是调用其父类(super class)构造函数之一。如果您不明确执行此操作,编译器会为您插入此指令。构造函数

 public B(int a) {
     mine-=a; 
     /*Some operation2...*/
 }

因此相当于

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

由于 A 没有无参数构造函数,因此编译失败。在这种情况下,您必须显式调用 super 构造函数之一:

public B(int a) {
    super(a);
    mine-=a; 
    /*Some operation2...*/
}

关于Java:将一个对象扩展到另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10474701/

相关文章:

java - 如何在 java 中的未映射网络打印机上打印 PDF?

java - 如何指示 ArrayAdapter 重绘其所有元素?

php - 使用哪种设计模式来动态构建表单。 PHP

c# - 难道真的不能垂头丧气吗?它对我来说很好用

java - 无法登录 Tomcat 管理器

java - 桌面应用程序基准测试

PHP:对象上的array_map?

php - PHP 中的 Bresenham 直线算法

c# - 派生的 C# 接口(interface)属性是否可以覆盖同名的基本接口(interface)属性?

虚拟继承函数的 C++ 内联