Java Question need help

https://www.codecademy.com/courses/learn-java/lessons/learn-java-methods/exercises/reassigning-instance-fields

in Java for the section object oriented java and the lesson about Method for the 6th page I had to write a code like this now this code runs perfect but i like to explore and test new things and was wondering why for the increasePrice Method why the (price = newPrice) had to be in the method because I tried moving it in the instance fields and found out the code doesn’t work if I do it like that why? it is a instance isn’t it?

class Store {
// instance fields
String productType;
double price;

// constructor method
public Store(String product, double initialPrice) {
productType = product;
price = initialPrice;
}

// increase price method
public void increasePrice(double priceToAdd){
double newPrice = price + priceToAdd;
price = newPrice;
}

// main method
public static void main(String args) {
Store lemonadeStand = new Store(“Lemonade”, 3.75);
lemonadeStand.increasePrice(1.5);
System.out.println(lemonadeStand.price);

}
}

Hi,

I’m not sure I understand the question fully so correct me if I’m wrong in what you’re asking about.

here:

public void increasePrice(double priceToAdd) {
  double newPrice = price + priceToAdd;
  price = newPrice;
}

can’t you just write?:

public void increasePrice(double priceToAdd) {
  price = price + priceToAdd;
}

Welcome to the forums :slight_smile:
In the future be sure to press </> before pasting so that the code comes out formatted.

1 Like

Remember that any variables defined inside methods are limited to the scope of that method and cannot be accessed outside of that method.

public static void calculateTax(double subtotal) {
  double tax = subtotal * 0.1;
}

System.out.println(tax); // throws an error
More

However, we can declare a variable (but not assign a value) outside of a method. In that case, its scope would be package-private, meaning that it is accessible within the class and package it is defined in. More on access modifiers here.

1 Like