gpt4 book ai didi

java - 构造函数和继承

转载 作者:行者123 更新时间:2023-11-29 06:02:27 25 4
gpt4 key购买 nike

我想知道如何在子类中使用父类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com