In the previous chapter, we used the term "variable" for the color property inside the Car class.
When a variable is part of a class, it is officially called an attribute (or sometimes a field or property). An attribute is a piece of data that belongs to the class.
You can access an object's attributes by using the dot notation (.).
First, create an object of the class (e.g., Car myCar = new Car();). Then, you can access the attributes with objectName.attributeName.
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
You can also modify the value of attributes using the dot notation.
public class Main {
int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Original value: " + myObj.x);
myObj.x = 25; // Modify the attribute value
System.out.println("New value: " + myObj.x);
}
}
final KeywordIf you don't want the ability to overwrite existing attribute values, you can declare the attribute as final.
The final keyword is useful for creating constants, similar to how it's used for variables. Once a final attribute is initialized, it cannot be changed.
public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
// myObj.x = 25; // This will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
Using final helps create more robust and predictable code by preventing accidental changes to important data.