Java Class Attributes: Understanding Variables Within a Class

Learn about Java class attributes, which are variables defined within a class. In this guide, we illustrate how attributes like x and y are used to store state and data for objects. Enhance your understanding of object-oriented programming by exploring how class attributes contribute to the structure and functionality of Java classes.



Java Class Attributes

Class attributes are variables within a class. For example, in the following class, x and y are attributes:

Syntax

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

Accessing Attributes

Create an object of the class and use the dot syntax to access attributes:

Syntax

public class Main {
int x = 5;

public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Output

5

Modify Attributes

You can change attribute values:

Syntax

public class Main {
int x;

public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}
Output

40

Or override existing values:

Syntax

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);
}
}
Output

25

Final Attributes

If you don't want to override values, declare the attribute as final:

Syntax

public class Main {
final int x = 10;

public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // Error: cannot assign value to a final variable
System.out.println(myObj.x);
}
}
Output

Error

Multiple Objects

Creating multiple objects allows changing attributes in one object without affecting the others:

Syntax

public class Main {
int x = 5;

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

5
25

Multiple Attributes

You can have as many attributes as you want:

Syntax

public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;

public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
Output

Name: John Doe
Age: 24