What a field is
An empty Dog class is a shell: every Dog object is identical to every other one, and none of them can remember anything. A field fixes that. It is a variable that belongs to a class, and every object created from the class gets its own copy of each field. Fields are also called instance variables, because each instance has its own.
Declaring fields
A field declaration goes in the class body, outside any method. It names the type and the field, just like a variable declaration:
class Dog {
public String name;
public int age;
}
Each declaration has three parts:
- an access modifier, here
public, which means any code can read and write the field. A later lesson introducesprivatefor fields that only the class itself should touch; - the type, such as
Stringorint; - the name, followed by a semicolon.
Reading and writing fields
You reach a field of one particular object with the dot operator:
Dog dog = new Dog();
dog.name = "Rex";
dog.age = 4;
System.out.println(dog.name);
The first two assignments write the fields, and the last line reads one, printing Rex. dog.age means "the age of this dog", so the dot attaches the field to a specific object.
Because each object has its own slot for every field, two dogs can hold different values without affecting each other:
Dog a = new Dog();
Dog b = new Dog();
a.age = 4;
b.age = 9;
System.out.println(a.age + " " + b.age);
This prints:
4 9
Default values
Unlike a local variable, a field doesn't have to be assigned before you read it. If you don't assign it, Java gives it a default value:
- numeric types such as
intanddoublestart at0; booleanstarts asfalse;- references, such as
String, arrays and other classes, start asnull.
Given a class with a String name, an int age and a boolean good field, a new object with nothing assigned prints this:
Dog d = new Dog();
System.out.println(d.name + " " + d.age + " " + d.good);
null 0 false
The text null appears because string concatenation turns a null reference into the word "null". Calling a method on that name, as in d.name.length(), would throw a NullPointerException instead.
The lesson's exercise, step by step
The starter code has an empty Dog class and a mainFunction that creates dog and then prints dog.name and dog.age. Two steps make it work:
- Declare the fields. Inside
Dog, add a publicStringcallednameand a publicintcalledage. They must bepublicso the code inSolution, a different class, may use them. - Assign values. In
mainFunction, below the line that createsdog, setdog.nameto"Rex"anddog.ageto4.
The program with both steps applied:
class Dog {
public String name;
public int age;
}
class Solution {
public void mainFunction() {
Dog dog = new Dog();
dog.name = "Rex";
dog.age = 4;
System.out.println(dog.name + " is " + dog.age + " years old");
}
}
Its output is:
Rex is 4 years old
If you skipped step 2, the program would still compile and would print null is 0 years old, which shows the default values at work.
Common mistakes
- Forgetting the type. A field needs a type:
public name;doesn't compile. - Using the class instead of an object.
Dog.name = "Rex";tries to treatnameas belonging to the class itself. Fields like these belong to individual objects, so use a variable such asdog.name. - Assigning to a field before creating the object. If
dogisnull, thendog.name = "Rex";throws aNullPointerException. Create the object withnewfirst. - Quotes around text, none around numbers. Write
dog.age = 4;, notdog.age = "4";, which fails because aStringcan't be stored in anint. The name needs quotes, because it is a string. - Missing
public. Without a modifier, a field is visible only to classes in the same package. The classes here happen to be in one file and one package, so it would still compile, butpublicstates the intent, and it is what the lesson uses. - Misspelling a field.
dog.namis a compile error, which is a helpful property: a typo can't silently create a new field.
Key takeaways
- A field is a variable declared inside a class but outside its methods.
- Every object has its own copy of each field.
- Use the dot operator, as in
dog.name, to read or write a field of a specific object. - Fields have defaults:
0for numbers,falseforbooleanandnullfor references. publiclets any code access a field. Later lessons show howprivateprotects it.