Java - Access Fields of a Class via Dot Notation

What is dot notation?

Dot notation is used to refer to instance variables.

Syntax

The general form of the dot notation syntax is

<Reference Variable Name>.<Instance Variable Name>

For the class of Employee

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

jack.name to refer to the name instance variable that jack variable is referring.

To assign a value to the name instance variable

jack.name = "Jack Pinkman";

To assign the value of the name instance variable to a String variable aName:

String aName = jack.name;

Access static variable

You have two ways to refer to a class variable using dot notation.

  • You can refer to a class variable using the name of the class: <Class Name>.<Class Variable Name>, for example, Employee.count
  • You can use a reference variable to refer to the class variable of a class. For example, jack.count.

Related Topic