本文介绍了从Java中的子类构造函数调用超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个构造函数,该构造函数将字段作为参数,然后将其放在存储在超类中的字段中。这是我正在使用的代码

I am trying to create a constructor that takes a field as a parameter, then puts it in a field that is stored in a superclass. Here is the code I am using

public crisps(String flavour, int quantity) {
    this.flavour = super.getFlavour();
    this.quantity = quantity;
}

在超类中,我用

private String flavour;

我有一个存取方法

public String getFlavour() {
    return flavour;
}

我收到错误 flavor在超类中有私人访问权限,但我相信这应该无关紧要,因为我正在调用将其返回到字段的访问器方法?

I am getting an error "flavour has private access in the superclass", but I believe this shouldn't matter as I am calling the accessor method that returns it to the field?

推荐答案

你应该做什么:

为你的超类添加一个构造函数:

Add a constructor to your super class:

public Superclass {
    public SuperClass(String flavour) {
       // super class constructor
       this.flavour = flavour;
    }
}

在Crisps类中:

public Crisps(String flavour, int quantity) {
    super(flavour); // send flavour to the super class constructor
    this.quantity = quantity;
}

 

评论

您的问题的一些评论:

在超类中,我用

private String flavour;

这不是初始化,而是声明。初始化是指你设置一个值。

This is not an initialization, it is a declaration. An initialization is when you set a value.

我收到一个错误的味道在超类中有私人访问但我相信这应该不重要因为我是调用将其返回到字段的访问器方法?

"I am getting an error " flavour has private access in the superclass" but I believe this shouldn't matter as I am calling the accessor method that returns it to the field?"

当你调用访问器(也称为getter)时,它没问题 - 取决于getter的可见性。
代码中的问题是:

When you call a accessor (aka getter), it is ok - depends on the getter visibility.The problem in you code is the:

this.flavour =

因为flavor不是在Crisps类上声明的字段,而是在supper类上,所以你不能像这样直接访问。你应该使用我的建议或在超类上声明一个setter:

because flavour is not a field declared on Crisps class, but on the supper class, so you can't do a direct access like that. you should use my suggestion or declare a setter on the super class:

public void setFlavour(String flavour) {
    this.flavour = flavour;
}

然后你可以在子类上使用它:

Then you can use it on the child class:

public Crisps(String flavour, int quantity) {
    this.quantity = quantity;
    super.setFlavour(flavour);
}

这篇关于从Java中的子类构造函数调用超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:08