-6

Whenever i create a goblin object and call the method isNice, it always return false. But when i do System.out.println(nice) it does it randomly.

public class Goblin
{

    private boolean nice;
    private boolean isNice;


    public Goblin()
    {
        // initialise instance variables
          Random rand = new Random();
         boolean nice = rand.nextBoolean();

    }

    public boolean isNice()
    {

            return true;

        else 
            return false;
    }

}

Marius Kuzm
  • 149
  • 9

1 Answers1

3
boolean nice = rand.nextBoolean();

is declaring and assigning a local variable. You aren't assigning the field, so it will always have its default value, false, when you access it with the getter.

Drop the boolean.

Andy Turner
  • 131,952
  • 11
  • 151
  • 228
  • To explain further: Since you didn't assign `nice` to true- `nice` will never equal true and thus the method `isNice()` always returns false. – chevybow Oct 30 '18 at 21:44