-1

I made 2 objects of the cereal class I made. One called frostedFlakes with the name "Frosted Flakes" and one called luckyCharms with the name "Lucky Charms". When I called on an accessor method I wrote to print the name of FrostedFlakes, it printed the name "Lucky Charms".

public class MyProgram
{
    public static void main(String[] args)
    {
        Cereal frostedFlakes = new Cereal("frosted Flakes");
        Cereal LuckyCharms = new Cereal("Lucky Charms");
        
        System.out.println(frostedFlakes.getName());

    }
}
    import java.io.*;
    public class Cereal {
    //static variables
    private static String name;
    
    //constructor
    Cereal(String name){
        this.name = name;
    }
    
    //accessor methods
    public static String getName(){
        return name;
    }
    
    }

I thought maybe there was a problem with the way I wrote the constructor or wrote the variables, so I experimented with both, yet received the same result.

  • `name` should not be `static`. That means there's only one instance of that variable across all the instances of `Cereal`. – tgdavies Apr 12 '23 at 06:02
  • name should be instance variable so it update and maintain multiple copy rather than single copy – Anand Dwivedi Apr 12 '23 at 06:03
  • In your own words, where the code says `private static String name;`, what did you expect that to mean? in particular, what did you expect `static` to do? – Karl Knechtel Apr 12 '23 at 06:34

1 Answers1

0

The constructor and everything is fine, but you shouldn't have declared name as a static variable.
This is because static variables are 'shared'* over all instances (objects) of your class; Thus being static -> In your instance this, this means, that once you've set 'name', it'll be shared across all instances of Cereal

*shared here simply means, that there will only be one instance of that specific variable, shared across all the objects of that class.

To make your code 'work', you simply have to remove the static keyword from your variable name.
This removes the one-instance-across-everything property from your variable and makes it 'object-specific'.

Little additional info: You typically only want to declare variables static, when they're global properties or values, which aren't going to be object-specific, such as e.g.

private static final int MAX_LENGTH_TEXT = 425

Hope this helped! Cheers

Z-100
  • 518
  • 3
  • 19