简体   繁体   中英

New programmer, need help. Assigning a field inherited from superclass to a variable inside a subclass' method

I want to assign the basePrice (which is inherited field from Hamburger class) to the double newPrice variable inside the overwritten addItems() method. This was not a problem in the super class since the field existed. I just typed "double newPrice = this.basePrice;". But, this is not working in the subclass. I'm new to programming, any help appreciated.

public class HealthyBurger extends Hamburger{

    public HealthyBurger(String meat, double basePrice) {
        super("Healthy Burger", "brown rye", meat, basePrice);
    }

    public void addItems() {
        double newPrice = ???HOW TO ASSISGN basePrice HERE???;
    }
}

To access this.basePrice from the derived class, basePrice attribute has to be protected in the base class.

Then you can do:

this.basePrice = ...; // whatever you want here

Most likely there is a method called getBasePrice() which you should invoke:

this.getBasePrice();
// instead of
this.basePrice;

If there isn't one, go to the source code of Hamburger ( Hamburger.java ) and add this method.

Explanation

If you get an error when you write this.basePrice in your HealthyBurger class, that means the field in the Hamburger class is either marked as private or, it BOTH [1] is in another package, and [2] has been declared with no access modifier (which is java-ese for a concept called package private - meaning, only things inside the package can touch it, and you're not in there).

One fix is to go into the source code of Hamburger.java and make it protected instead (which means: Any source code in this file, all classes in the same package, and any subclasses - and that last one will open up the doors for you), but it is more idiomatic java to make fields private, so leave it as is, and make this method, which is called a 'getter', and should probably be public .

NB: If you find it tedious to write these, there's always Lombok .

You can just create a getBasePrice() method defined in the parent class or just declare the field:

protected double basePrice

and you can just assign double newPrice = this.basePrice;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM