Java - Accessing class variables and instance variables of a class


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


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 Pinkman";
    jack.gender = "Male";

    // Read and print the values of name, gender and count
    String jackName =;
    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 = "Tom";

    // Read and print the changed name
    String changedName =;
    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


Related Example