Java - Class fields vs Instance fields

Field Type

Java lets you declare two types of fields for a class:

  • Class fields
  • Instance fields

Class fields are class variables.

Instance fields are instance variables.

A class variable is also known as a static variable. an instance variable is also known as a non-static variable.

class Employee {
        String name;
        String gender;
}

In the above code, name and gender are two instance variables of the Employee class.

All class variables must be declared using the static keyword as a modifier.

Declaration of a Employee Class with One Class Variable and Two Instance Variables

class Employee {
        String name;        // An instance variable
        String gender;      // An instance variable
        static long count;  // A class variable because of the static modifier
}

Difference

Class field only have one instance while the instance field can have as many instances as you create.

Related Topic