M
M
Menson2017-01-18 16:40:44
Java
Menson, 2017-01-18 16:40:44

Where to place variables: class or method?

Hello! Explain, please, such nuance: where to declare variables?!

// Пример 1:
class Cat1 {
  int ht;

  public void setSize(final int size) {
    if (size > 9) {
      ht = size;
      System.out.println("Размер кошки " + ht);
    } else {
      System.out.print("не бывает таких кошек");
    }
  }
}

// Пример 2:
class Cat2 {

  int ht = 0;

  public void setSize(final int size) {
    if (size > 9) {
      ht = size;
      System.out.println("Размер кошки " + ht);
    } else {
      System.out.print("не бывает таких кошек");
    }
  }
}

// Пример 3:
class Cat3 {
  public void setSize(final int size) {
    int ht;
    if (size > 9) {
      ht = size;
      System.out.println("Размер кошки " + ht);
    } else {
      System.out.print("не бывает таких кошек");
    }
  }
}

// Пример 4(так уже почему-то нельзя):
class Cat4 {
  public void setSize(final int size) {
    int ht = 0;
    if (size > 9) {
      ht = size;
      System.out.println("Размер кошки " + ht);
    } else {
      System.out.print("не бывает таких кошек");
    }
  }
}

Examples 1 to 3 give the same result no matter where I declared the variable (assigned the value);
Example 4 is invalid for some reason..
Thanks in advance for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Shishkin, 2017-01-18
@Menson

Inside the method are variables that are necessary and will be used only during the execution of this method. Variables are placed inside the class, which speak about the state of the object generated from this class. And as a rule, these variables are made private + getters and setters are created for them. In your example, the cat's size is indicative of its "state", so it makes sense to store the variable in a class.
public class Cat {
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
if(size <= 9) throw new IllegalArgumentException("Cat size should be more than 9");
this.size = size;
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question