Java - Accessing class variables and instance variables of a class

Introduction

The following code shows how to access class variables and instance variables of a class.

Demo

public class Main {
  public static void main(String[] args) {
    // Create an instance of Employee class
    Employee jack = new Employee();

    // Increase count by one
    Employee.count++;//  w  w w  .  j  av  a2 s  .c  o m

    // Assign values to name and gender
    jack.name = "Jack Pinkman";
    jack.gender = "Male";

    // Read and print the values of name, gender and count
    String jackName = jack.name;
    String jackGender = jack.gender;
    long population = Employee.count;

    System.out.println("Name: " + jackName);
    System.out.println("Gender: " + jackGender);
    System.out.println("Population: " + population);

    // Change the name
    jack.name = "Tom";

    // Read and print the changed name
    String changedName = jack.name;
    System.out.println("Changed Name: " + changedName);
  }
}

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

Result

Related Example