Java - Class Field Definition

What is field?

Fields of a class represent properties or attributes of that class.

For example, Employee class can have two properties: a name and a gender.

Syntax

The general syntax to declare a field in a class is

<modifiers> class ClassName {

    <modifiers> <data type> fieldName = initValue;
    <modifiers> <data type> fieldName;//without initial value
}

A field declaration can use zero or more modifiers.

Optionally, you can initialize each field with a value.

Example

The following code shows how to add two fields, name and gender, to the declaration of the Employee class.

class Employee {
        String name;
        String gender;
}

The Employee class declares two fields: name and gender.

Both fields are of the String type.

Every instance of the Employee class will have a copy of these two fields.

Related Topics

Example