Loading lessons...
Class Attributes
Class Attributes
Attributes are variables inside a class. They describe the state of an object.
Declaring attributes
public class Main {
int x = 5;
int y = 3;
}
Accessing attributes
Use the object name, a dot, then the attribute name:
Main myObj = new Main();
System.out.println(myObj.x); // 5
Modifying attributes
Assign a new value through the object:
myObj.x = 25;
System.out.println(myObj.x); // 25
Override existing values
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:
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. finalattributes cannot be changed.- Each object keeps its own attribute values.