Junior — Middle
What criteria and conditions must fields in a class satisfy?
sobes.tech AI
Answer from AI
In Java, class fields should meet the following criteria and conditions:
- Initialization: fields can be initialized at declaration or in the class constructor.
- Access modifiers: usually fields are made private to encapsulate data, with access managed through getter and setter methods.
- Data types: fields must have a defined type (primitive or reference).
- Constants: if a field should be immutable, it is declared with
finalandstaticmodifiers (e.g., constants). - Static fields: if a field belongs to the class as a whole, not to a specific object, it is declared as
static.
Example:
public class Person {
private String name; // private field
private int age;
public static final String SPECIES = "Homo sapiens"; // constant
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}