Lesson 27 +10 XP

Class Attributes

Attributes are variables inside a class. They describe the state of an object.

Declaring attributes


java
public class Main {
  int x = 5;
  int y = 3;
}

Accessing attributes

Use the object name, a dot, then the attribute name:


java

### Main myObj = new Main();

### System.out.println(myObj.x); // 5

Modifying attributes

Assign a new value through the object:


java
myObj.x = 25;

### System.out.println(myObj.x); // 25

Override existing values


java
public class Main {
  int x = 10;

public static void main(String[] args) {

### Main myObj = new Main();
    myObj.x = 25; // x is now 25

### System.out.println(myObj.x);
  }
}

Final attributes

The final keyword makes an attribute unchangeable:


java
final int x = 10;
// x = 25;  this would cause an error

Multiple objects have separate attributes

Changing x on one object does not change x on another object of the same class.

TL;DR

  • Attributes are variables that belong to a class.
  • Access them with object.attribute.
  • final attributes cannot be changed.
  • Each object keeps its own attribute values.