Start learning free

LESSON 179 OF 344 · OBJECT-ORIENTED PROGRAMMING

Class Fields in Java: Declaring and Using Instance Variables

Lesson Read the full explanation

TL ; DR:

  • A field is a variable that lives inside a class. Each object of that class has its own copy.


  • Declare a field with a type and a name, with public in front so other code can read and write it:

    class Dog {
        public String name;
        public int age;
    }
    

  • Access a field on an object with the dot operator: dog.name = "Rex";



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical to every other one. We need a way to attach data to each object.

That's what fields are for. A field is a variable that belongs to a class — and each object created from that class gets its own copy of every field.


Declaring fields

class Dog {
    public String name;
    public int age;
}
  • public means "any code can read and write this field". You'll see private later for fields that should only be touched by the class itself.

  • String name; is just a variable declaration — same syntax you'd use anywhere else.


Reading and writing fields

Dog dog = new Dog();
dog.name = "Rex";        // write
dog.age = 4;
System.out.println(dog.name);   // read → prints "Rex"

Each object has its own slot for every field, so two dogs can have different names without interfering.


Default values

If you don't assign a field, Java fills it in for you:

  • Numbers default to 0

  • boolean defaults to false

  • References (String, arrays, other classes) default to null


Your task

Update the Dog class to have two fields: name (a String) and age (an int). Then in mainFunction, set them on the dog object so the pre-filled System.out.println prints:

Rex is 4 years old
STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · OBJECT-ORIENTED PROGRAMMING

    Class Fields in Java, explained

    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 introduces private for fields that only the class itself should touch;
    • the type, such as String or int;
    • 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 int and double start at 0;
    • boolean starts as false;
    • references, such as String, arrays and other classes, start as null.

    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:

    1. Declare the fields. Inside Dog, add a public String called name and a public int called age. They must be public so the code in Solution, a different class, may use them.
    2. Assign values. In mainFunction, below the line that creates dog, set dog.name to "Rex" and dog.age to 4.

    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 treat name as belonging to the class itself. Fields like these belong to individual objects, so use a variable such as dog.name.
    • Assigning to a field before creating the object. If dog is null, then dog.name = "Rex"; throws a NullPointerException. Create the object with new first.
    • Quotes around text, none around numbers. Write dog.age = 4;, not dog.age = "4";, which fails because a String can't be stored in an int. 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, but public states the intent, and it is what the lesson uses.
    • Misspelling a field. dog.nam is 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: 0 for numbers, false for boolean and null for references.
    • public lets any code access a field. Later lessons show how private protects it.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free