Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

Calling superclass from a subclass constructor in 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;
}

In the superclass I have initialised the field with

private String flavour;

and I have an accessor method

public String getFlavour() {
    return flavour;
}

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you should do:

Add a constructor to your super class:

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

In the Crisps class:

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

 

Comments

Some comments to your question:

"In the superclass I have initialised the field with "

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?"

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

this.flavour = 

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...