I was wondering how to use a superclass constructor in a subclass but need to instantiate fewer attributes in the subclass. Below are the two classes. I’m not even sure if I’m doing things right currently. In the second class, there’s an error that says “Implicit super constructor PropertyDB() is undefined. Must explicitly invoke another constructor.” Note that this code is obviously incomplete and there is code that’s commented out.
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;
}
}
implicit constructor
PropertyDB()exists only if you do not define any other constructors, in which case you will have to explicitly definePropertyDB()constructor.The reason you see this error “Implicit super constructor PropertyDB() is undefined. Must explicitly invoke another constructor.” is that in your
public FarmedLand(int newHectares, int newListPrice, String newCorn)constructor,super()is automatically called as the first statement, which does not exist in your superclass.Here’s a simplified example:
can be instantiated by using
A a = new A()becausepublic A() { }is an implicit constructor of class A.can not be instantiated using
A a = new A()because by defining an explicit constructorpublic A(int z)the implicit one is no longer available.Moving onto constructors and inheritance, from Java Language Specification section 8.8.7:
So in your case the first statement executed in
public FarmedLand(int newHectares, int newListPrice, String newCorn)constructor is an implicit call tosuper();, which in your case is not defined implicitly (there’s already apublic PropertyDB(int, String, ...)constructor defined) or explicitly (it’s not in the source code)