Java is a popularly used object-oriented programming language that revolves around classes and objects. A class in Java can have different variables, methods, and constructors. These methods and variables represent the properties/characteristics and behavior of a class. Variables in Java are commonly known as attributes or fields. The variables declared within a Java class are called class attributes. For example, in the following image, “EmpDetails” is a class while “empID”, “empName”, and “empSalary” are its attributes:
Today, you will learn how to declare, access, and modify the class attributes in Java using suitable examples.
How to Create and Access a Class Attribute in Java
A class attribute is declared with a particular data type and an access modifier (public, protected, etc.). You can access a class attribute using the object of the class to which it belongs. Consider the following example for a profound understanding of class attributes:
package javaexamples;
public class CustomerInfo {
// creating a class attribute
int customerId = 1;
public static void main(String args[]) {
// creating a class object
CustomerInfo obj = new CustomerInfo();
// accessing class attribute
System.out.println("Customer ID: " + obj.customerId);
}
}
We create an integer-type class attribute and access it from the main() method using the class object. Finally, we execute the code and get the following result:
Note: Since we did not specify an access modifier for the class attribute, so by default it is set to “Default”.
How to Create and Access Multiple Class Attributes in Java
You can create as many class attributes as you desire. In the following example, we create three attributes of different data types:
package javaexamples;
public class CustomerInfo {
// creating multiple class attributes
int customerId = 1;
String customerName = "Joseph";
String customerAddress = "New York";
public static void main(String args[]) {
// creating a class object
CustomerInfo obj = new CustomerInfo();
// accessing class attributes
System.out.println("Customer ID: " + obj.customerId);
System.out.println("Customer Name: " + obj.customerName);
System.out.println("Customer Address: " + obj.customerAddress);
}
}
We create a class object and access all three attributes using the created class object:
How to Create and Access Static Class Attributes in Java
Java allows you to create static attributes (at class level only). These attributes are accessible without creating the class object. If you want to access a static attribute from another class, use the class name along with the attribute name, i.e., “ClassName.attributeName”.
Here is a practical demonstration of static attributes in Java:
package javaexamples;
public class CustomerInfo {
// creating static class attributes
static int customerId = 1;
static String customerName = "Joseph";
static String customerAddress = "New York";
static String productPurchased = "Laptop";
public static void main(String args[]) {
// accessing static class attributes
System.out.println("Customer ID: " + customerId);
System.out.println("Customer Name: " + customerName);
System.out.println("Customer Address: " + customerAddress);
System.out.println("Customer Product Purchased: " + productPurchased);
}
}
In this example, we create an integer and three string-type static attributes. We access all these attributes from the main() method without creating any instance of the class:
How to Re-assign or Modify a Class Attribute in Java
In Java, you can reassign/modify class attributes, as illustrated in the following example:
package javaexamples;
public class CustomerInfo {
// creating static class attributes
static int customerId = 1;
static String customerName = "Joseph";
String productPurchased = "Laptop";
public static void main(String args[]) {
CustomerInfo obj = new CustomerInfo();
// reassigning static class attributes
customerName = "John";
// reassigning non-static class attributes
obj.productPurchased = "MacBook Pro";
// accessing and printing class attributes
System.out.println("Customer ID: " + customerId);
System.out.println("Customer Name: " + customerName);
System.out.println("Customer Product Purchased: " + obj.productPurchased);
}
}
In this example:
- Initially, we declare and initialize a couple of static and a non-static class attribute.
- In the main() method, we create an object of this class to access its non-static attributes.
- After this, we re-assign the attributes “customerName” and “purchasedProduct”. The static attribute is modified without a class object while the non-static attribute is modified via the class object.
- Finally, we print the attributes on the console:
The output shows that the modified attribute values are retrieved.
How to Create Unmodifiable Class Attributes/Fields in Java
To create unmodifiable class attributes, use the “final” keyword in the attribute definition. If you try to override a final attribute, you will encounter an error, as demonstrated below:
package javaexamples;
public class Examples {
// creating a final attribute
final Double pi = 3.1415926;
public static void main(String args[]) {
Examples obj = new Examples();
obj.pi = 3.2;
System.out.println("The Value of PI: " + obj.pi);
}
}
We face a compile time error when we try to modify/alter the value of the “pi” attribute. However, for better understanding, we explicitly run the program, and as a result, we get the error “final field Examples.pi cannot be assigned”:
How to Access a Class Attribute With Multiple Objects of the Same Class
In Java, we can create multiple objects of the same class. This helps us alter/change the attribute values of one object without affecting the others.
Let’s understand the concept of multiple objects using the following example:
package javaexamples;
public class CustomerInfo {
// creating multiple class attributes
int customerId = 1;
String customerName = "Joseph";
String customerAddress = "New York";
public static void main(String args[]) {
// creating class objects
CustomerInfo obj1 = new CustomerInfo();
CustomerInfo obj2 = new CustomerInfo();
//modifying class attributes using obj2
obj2.customerId = 2;
obj2.customerName = "Ambrose";
obj2.customerAddress = "Chicago";
// accessing class attributes using obj1
System.out.println("Customer ID: " + obj1.customerId);
System.out.println("Customer Name: " + obj1.customerName);
System.out.println("Customer Address: " + obj1.customerAddress);
System.out.println("===========================");
// accessing class attributes using obj2
System.out.println("Customer ID: " + obj2.customerId);
System.out.println("Customer Name: " + obj2.customerName);
System.out.println("Customer Address: " + obj2.customerAddress);
}
}
In this example,
- We create two objects of the “CustomerInfo” class: “obj1” and “obj2”.
- Using the second object, we modify all the class attributes.
- After this, we use both objects to access and print the class attributes.
- The output proves that the second object has successfully modified the class attributes without affecting the attribute values of the first object:
How to Resolve the “attribute has private access” Error
The accessibility scope of the private attributes is restricted to the same class only. If we try to access or modify a private class attribute from another class, we will face the stated error:
package javaexamples;
class JavaDeveloper {
Integer developerID = 1;
private String developerName = "Ambrose";
}
public class Programmers {
public static void main(String args[]) {
JavaDeveloper obj = new JavaDeveloper();
System.out.println("ID of Java Programmer: " + obj.developerID);
System.out.println("Name of Java Programmer: " + obj.developerName);
}
}
In this example:
- We create two classes: “JavaDeveloper” and “Programmers”.
- Within the “JavaDeveloper” class we create a default and a private attribute.
- In the Programmers class, we create the object of the “JavaDeveloper” class and try to access both the attributes of the “JavaDeveloper” class using the created object.
- As a result, we encounter the following compile time error:
To fix this error, we can implement the concept of getters and setters:
package javaexamples;
class JavaDeveloper {
Integer developerID = 1;
private String developerName = "Ambrose";
// Getter for developerName
public String getDevName() {
return developerName;
}
// Setter for developerName
public void setDevName(String developerName) {
this.developerName = developerName;
}
}
public class Programmers {
public static void main(String[] args) {
JavaDeveloper obj = new JavaDeveloper();
// Using setter to modify a private attribute
obj.setDevName("Seth");
//getting a default attribute of JavaDeveloper class
System.out.println("The ID of Java Developer: " + obj.developerID);
// Using getter method to get the attribute values
System.out.println("The Name of Java Developer: " + obj.getDevName());
}
}
Here,
- In the “JavaDeveloper” class, we create a getter and a setter method for the private class attribute.
- The getter method “getDevName()” allows us to get the value of a private attribute “developerName” outside the “JavaDeveloper” class.
- Similarly, the setter method “setDevName” helps us modify the private attribute of the “JavaDeveloper” class from the “Programmers” class.
- In the “Programmers” class, we create the object of the JavaDeveloper class. We access the setDevName() method of the JavaDeveloper class using the created object and modify the value of a private attribute “developerName”.
- Finally, we access the getDevName() method of the JavaDeveloper class to retrieve the modified name:
This is how you can create, access, and modify the class attributes in Java.
Final Thoughts
In a nutshell, class attributes are variables contained by a specific class. They represent the characteristics of a class and are also known as fields. These attributes can be static or non-static. The static attributes are accessed without a class instance while non-static attributes must be accessed using the class object. Class attributes are modifiable, however, you can create unmodifiable attributes using the final keyword. In this Java guide, we have demonstrated all these concepts using appropriate examples.