Fields are declared outside of a class’s methods and are usually found right below the class declaration. Fields can be accessed by all methods of a class.
They can also be accessed from other classes (unless they are private) using the dot operator.
If a field is marked with static, its class name is used to reference it.
If a field is not static, an object of its class is used to reference it.
public class Man { public String name; //this is a field public static String gender = "Male"; //this is a static field public Man(String newName) { name = newName; //assigns the value of a field from within a method } }
and the other class
public class Main { public static void main(String[] args) { Man bob = new Man("Bob"); System.out.println(bob.name); //referenced from object, prints Bob System.out.println(Man.gender); //referenced from class name, prints Male } }
For more control over the field: https://en.wikipedia.org/wiki/Mutator_method#Java_example