Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
class egg extends food{
    double protein;
    double fats;
    double carbs;
    public egg(protein, fats, carbs){//declaring outside the parameters
        this.protein = protein;
        this.fats = fats;
        this.carbs = carbs;
    }
   }


What I have tried:

Java
class egg extends food{
    double protein;
    double fats;
    double carbs;
    public egg(protein, fats, carbs){//declaring outside the parameters
        this.protein = protein;
        this.fats = fats;
        this.carbs = carbs;
    }
   }
Posted
Updated 16-Jul-22 6:39am
v2
Comments
0x01AA 16-Jul-22 9:54am    
You should show also your class food.
SamuelKalubi 16-Jul-22 9:59am    
yes food is an abstract class
0x01AA 16-Jul-22 10:01am    
Show the code of that class, or is it confidential?

No.
When you declare variables at class level:
class egg extends food{
   double protein;
   double fats;
   double carbs;
You are saying "I need these to exist as separate items for each instance of the class I create" and they are available to all code within the class.

When you create variables as parameters they are local top that metho: they are created when the method is called, and destroyed when the method ends. They are not the same as class level variables even if they have the same name.
In fact, if you had correctly declared your constructor method parameters:
public egg(double protein, double fats, double carbs){
   ...
then they would do something called variable shadowing, which means that they would "hide" the class level variables of the same name and you wouldn't be able to get at the class level versions at all (unless you prefixed them with this which always references the current instance of the class:
public egg(double protein, double fats, double carbs){
   this.protein = protein;
   ...
Using this tells the compiler "which version" of the variable you are talking about in each case.
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900