java - 构造函数和继承

标签 java inheritance constructor

我想知道如何在子类中使用父类(super class)构造函数,但需要在子类中实例化较少的属性。下面是两个类。我什至不确定我目前做的事情是否正确。在第二个类中,有一个错误提示“隐式 super 构造函数 PropertyDB() 未定义。必须显式调用另一个构造函数。”请注意,这段代码显然是不完整的,并且有代码被注释掉了。

public abstract class PropertyDB {

private int hectares;

    private String crop;

    private int lotWidth;

    private int lotDepth;

    private int buildingCoverage;

    private int lakeFrontage;

    private int numBedrooms;

    private int listPrice;


    //public abstract int getPricePerArea();
    //public abstract int getPricePerBuildingArea();

    public PropertyDB(int newHectares, String newCrop, int newLotWidth, int newLotDepth, 
            int newBuildingCoverage, int newLakeFrontage, int newNumBedrooms, int newListPrice){
        hectares = newHectares;
        crop = newCrop;
        lotWidth = newLotWidth;
        lotDepth = newLotDepth;
        buildingCoverage = newBuildingCoverage;
        lakeFrontage = newLakeFrontage;
        numBedrooms = newNumBedrooms;
        listPrice = newListPrice;
    }
}


public class FarmedLand extends PropertyDB{


    public FarmedLand(int newHectares, int newListPrice, String newCorn){
        //super(270, 100, "corn");

        hectares = newHectares;
        listPrice = newListPrice;
        corn = newCorn;
    }
}

最佳答案

隐式构造函数 PropertyDB() 仅在您未定义任何其他构造函数时存在,在这种情况下,您必须显式定义 PropertyDB() 构造函数。

您看到此错误的原因“隐式 super 构造函数 PropertyDB() 未定义。必须显式调用另一个构造函数。”是在你的 public FarmedLand(int newHectares, int newListPrice, String newCorn) 构造函数中, super() 被自动调用为第一条语句,它在你的父类(super class)中不存在.

这是一个简化的例子:

public class A { }

可以使用 A a = new A() 实例化,因为 public A() { } 是类 A 的隐式构造函数。

public class A {
    public A(int z) { /* do nothing*/ }
}

不能使用 A a = new A() 实例化,因为通过定义显式构造函数 public A(int z) 隐式一个不再可用。

转到构造函数和继承,来自 Java Language Specification section 8.8.7 :

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

所以在你的例子中,在 public FarmedLand(int newHectares, int newListPrice, String newCorn) 构造函数中执行的第一条语句是对 super(); 的隐式调用,它在你的情况下没有隐式定义(已经定义了 public PropertyDB(int, String, ...) 构造函数)或显式定义(它不在源代码中)

关于java - 构造函数和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628462/

相关文章:

java - 如何让 Java 线程通知自己?

Java 复制构造函数 ArrayLists

c++ - 使用 new 创建指针数组,使其不被初始化为 NULL

java - java.time.LocalDate 导入失败

java - 计算字母频率,也涉及双字母

ruby-on-rails - 在 Ruby on Rails 中,如果我们生成了一个模型 "Animal",现在想要有 "Dog",我们应该怎么做?

c++ - 派生对象之间的特殊交互(即多重分派(dispatch))

c++ - 虚拟成员函数和非虚拟成员函数的调用方式有何区别?

javascript - 如何修改对象构造函数

java - 客户端在浏览器中输入的日期不会保存在 java POJO 中(客户端发送的请求在语法上不正确)