How to Access (Read/Write) Class Variables and Instance Variables of a Class - Java Object Oriented Design

Java examples for Object Oriented Design:Field

Description

How to Access (Read/Write) Class Variables and Instance Variables of a Class

Demo Code

class Human { //from  w ww .jav a  2s . c  om
    String name;        // An instance variable 
    String gender;      // An instance variable 
    static long count;  // A class variable because of the static modifier 
} 

public class Main {  
  public static void main(String[] args) {
    Human jack = new Human();
    // Increase count by one
    Human.count++;
  
    // Assign values to name and gender
    jack.name = "Ana";
    jack.gender = "Female";
  
    // Read and print the values of name, gender and count
    String jackName = jack.name;
    String jackGender = jack.gender;
    long population = Human.count;
  
    System.out.println("Name: " + jackName);
    System.out.println("Gender: " + jackGender);
    System.out.println("Population: " + population);
  
    // Change the name
    jack.name = "Jackie Parker";
  
    // Read and print the changed name
    String changedName = jack.name;
    System.out.println("Changed Name: " + changedName);
  }
}

Related Tutorials