Answer the question
In order to leave comments, you need to log in
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("не бывает таких кошек");
}
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question