向超类传递参数

5

嗨,大家好,我正在尝试使用构造函数来接受大量变量,然后将相关信息传递给超类构造函数。

我遇到的错误是,当我使用this.variable时,它告诉我在类中创建该变量,但我认为调用super可以让我以这种方式使用它。

public class AuctionSale extends PropertySale {

private String highestBidder;   
public AuctionSale(String saleID, String propertyAddress, int reservePrice, String    highestBidder) {
    super(saleID, propertyAddress, reservePrice);
    this.saleID = saleID;
    this.propertyAddress = propertyAddress;
    this.reservePrice = reservePrice;
    this.highestBidder = "NO BIDS PLACED";
}

正如你所看到的,我调用了超类propertysale来获取变量。

超类 -

public class PropertySale {
// Instance Variables
private String saleID;
private String propertyAddress;
private int reservePrice;
private int currentOffer;
private boolean saleStatus = true;

public PropertySale(String saleID, String propertyAddress, int reservePrice) {
    this.saleID = saleID;
    this.propertyAddress = propertyAddress;
    this.reservePrice = reservePrice;
}

还有很多其他的构造函数,但我认为它们现在并不重要。


你能发布一下你的超类吗? - Sanjaya Liyanage
3个回答

7
您遇到错误的原因是因为在PropertySale类中,以下变量具有private访问权限:PropertySale
saleID
propertyAddress
reservePrice

如果超类没有声明变量为 protectedpublic,则您不能在子类 AuctionSale 中访问它们。但是,在这种情况下,这是不必要的:您将这三个变量传递给 super 构造函数,因此它们会在基类中设置。在派生类的构造函数中,您只需要调用 super,然后处理已经声明的派生类变量,就像这样:

public AuctionSale(String saleID, String propertyAddress, int reservePrice, String    highestBidder) {
    super(saleID, propertyAddress, reservePrice);
    this.highestBidder = "NO BIDS PLACED";
}

2
是的,就像dasblinkenlight所写的那样。此外,您不需要指定“this。”; 您只需执行highestBidder =“未竞标”即可正常工作。大多数情况下,“this。”仅需要用于消除类成员与局部变量之间的歧义。 - Edward Falk

4

私有变量仅在声明它们的类中可以访问,其他地方无法访问。受保护或公共变量可以在子类中访问。

那么将类的变量传递给自己的构造函数有什么用处呢?

您的saleIDpropertyAddressreservePrice都是超类中的私有变量。这限制了其使用。

然而,您通过超类的构造函数设置变量,因此不必自己设置...

public class AuctionSale extends PropertySale {

private String highestBidder;   
public AuctionSale(String saleID, String propertyAddress, int reservePrice, String    highestBidder) {
    super(saleID, propertyAddress, reservePrice);//This should be sufficient
    //this.saleID = saleID;
    //this.propertyAddress = propertyAddress;
    //this.reservePrice = reservePrice;
    this.highestBidder = "NO BIDS PLACED";
}    

如果您想访问私有变量,最佳实践是在超类中编写 gettersetter 方法,并在需要时使用它们。


2
你在超类中把变量标记为私有的,这意味着它们将不会被继承。请将它们标记为公开、默认或受保护,并测试一下。私有字段只能在类本身中访问。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接