Attributes


Class attributes/fields are variables within a class. The example creates a class called MyClass with two attributes: x and y:
public class MyClass {
  int x = 5;
  int y = 3;
}

Accessing Attributes
The dot syntax (.) can be used to access class attributes. The example creates an object myObj of the MyClass class, and then uses the x attribute on the object to print its value:
public class MyClass {
  int x = 5;
  public static void main( String[ ] args ) {
    MyClass myObj = new MyClass( );
    System.out.println( myObj.x ); 
  }   // Output: 5
}

Modifying Attributes
The example sets the value of x to 4. If you want a variable to always store the same value, like PI (3.14159...), declare the attribute as final:

    final int x = 5;
public class MyClass {
  int x;
  public static void main( String[ ] args ) {
    MyClass myObj = new MyClass( );
    myObj.x = 4;
    System.out.println( myObj.x );
  }   // Output: 4
}

Multiple Objects
If you create multiple objects of one class, you can change the attribute values in one object, without affecting the attribute values in the other.

For example, change the value of x to 4 in myObj2, and leave x in myObj1 unchanged:
public class MyClass {
  int x = 5;

  public static void main( String[ ] args ) {
    MyClass myObj1 = new MyClass( );  // Object 1
    MyClass myObj2 = new MyClass( );  // Object 2
    myObj2.x = 4;
    System.out.println( myObj1.x );   // Output: 5
    System.out.println( myObj2.x );   // Output: 4
  }
}