Introduction to Class Attributes
We can define variables inside a class that represent the properties or characteristics of the objects; it is called Java class attributes.
Every object of a class can have its own set of values for these attributes, allowing each object to maintain its individual state.
This concept is essential because attributes are a key part of Java’s object-oriented programming, as they allow us to store and manage data for objects effectively.
Syntax for Class Attributes in Java
In Java, a class attribute is an instance variable that is declared inside a class but outside any method, constructor, or block. These attributes define the properties or characteristics of the objects that created from the class.
The basic syntax for declaring a class attribute is:
class ClassName {
dataType attributeName; // Declaration of an attribute
}
Explanation of this syntax:
1) class ClassName: This defines a new class “ClassName”. You can replace it with any meaningful name representing the type of object you want to create.
2) dataType: Every attribute must have a data type, which tells Java what kind of data the attribute can hold. For example of data types:
- Primitives types: int, double, Boolean, char.
- Non-primitive types: String, arrays, or other objects
3) attributeName: This is the name of the attribute. It should follow Java naming conventions like:
- Start with a letter, _ or $
- Use camelCase for readability (camelCase means, single word start with small latter but second word is capitalized.
- Remember this thing, attributeName should not be a Java keyword.
4) Optional Initialization:
We can also assign an initial value to the attribute while declaring it:
class Car {
String color = "Red"; // Attribute with default value
int speed = 100;
}
5) Access Modifiers (Optional): It means you give control over the visibility of attributes. Let’s understand these concepts clearly:
- public: It is accessible from anywhere in any class.
- private: This modifier is accessible only inside the class.
- protected: It is accessible in the class, package, and subclasses.
- Default (no modifier): accessible within the same package.
Simple example with access modifiers:
class Car {
private String model; // private attribute
public int year; // public attribute
}
We will discuss all these types in further topics at an advanced level. Click Here…
How To Define a Class Attributes in Java
Code example:
class Student {
String name; // Attribute
int age; // Attribute
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Amit";
s1.age = 20;
Student s2 = new Student();
s2.name = "Neha";
s2.age = 22;
System.out.println(s1.name + " is " + s1.age + " years old.");
System.out.println(s2.name + " is " + s2.age + " years old.");
}
}
Output:
Amit is 20 years old.
Neha is 22 years old.
In this example, name and age are class attributes, and each Student object has its own values.
Types of Class Attributes in Java
Class attributes are categorized into two main types: instance attributes and static attributes.
1) Instance Attributes:
- These attributes belong to individual objects of a class. Each object has its own copy of these attributes, and defined without the static keyword.
Example:
class Car {
String brand; // Instance attribute
String color; // Instance attribute
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
car1.color = "Red";
Car car2 = new Car();
car2.brand = "Honda";
car2.color = "Blue";
System.out.println("Car 1: " + car1.brand + ", " + car1.color);
System.out.println("Car 2: " + car2.brand + ", " + car2.color);
}
}
Output:
Car 1: Toyota, Red
Car 2: Honda, Blue
- Each Car object has its own brand and color. It means one object’s attribute does not affect the other.
2) Static Attributes:
- These attributes belong to the class itself, not individual objects, and all objects of the class share the same copy of a static attribute.
- It is declared inside the class using the static keyword.
Example:
class Car {
static int wheels = 4; // Static attribute
}
public class Main {
public static void main(String[] args) {
System.out.println("All cars have " + Car.wheels + " wheels.");
// Changing static attribute
Car.wheels = 6;
System.out.println("After modification, all cars have " + Car.wheels + " wheels.");
}
}
Output:
All cars have 4 wheels.
After modification, all cars have 6 wheels.
- The wheels attribute is shared among all Car objects. If we change it in the class, it will affect all objects, because it belongs to the class, not a single object.
Accessing Class Attributes
- Instance Attributes: We can access and modify attributes using the dot ( . ) operator.
car1.brand = "Toyota";
- Static Attributes: Accessed via class name and the dot (.) operator.
Car.wheels = 4;
Advanced Concepts Related to Attributes
Java also supports advanced types of attributes that have special behaviors: final attributes and transient attributes.
1) Final Attributes
A final attribute is a variable whose value cannot be changed once it is assigned. This is useful for constants, maximum limits, or any value that should never change during program execution.
For example:
class Circle {
final double PI = 3.14159; // Final attribute
double radius;
Circle(double radius) {
this.radius = radius;
}
double calculateArea() {
return PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Circle c1 = new Circle(5);
System.out.println("Area of circle: " + c1.calculateArea());
}
}
Output:
Area of circle: 78.53975
- In this code, PI is final, so its value cannot be changed anywhere in the code.
2) Transient Attributes
A transient attribute is not saved during serialization.
Serialization is the process of converting an object into a stream of bytes, typically to save to a file or send over a network.
It is useful for sensitive data (like passwords) or temporary data that you don’t want to save permanently.
For example:
import java.io.*;
class User implements Serializable {
String username;
transient String password; // This attribute will NOT be saved during serialization
User(String username, String password) {
this.username = username;
this.password = password;
}
}
public class Main {
public static void main(String[] args) throws Exception {
User u1 = new User("Alice", "mySecret123");
// Serialize object
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.ser"));
out.writeObject(u1);
out.close();
// Deserialize object
ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.ser"));
User u2 = (User) in.readObject();
in.close();
System.out.println("Username: " + u2.username); // Saved and loaded
System.out.println("Password: " + u2.password); // null because it's transient
}
}
Output:
Username: Alice
Password: null
- You can see, the username is serialised normally.
- The password is transient, so it does not get saved. After deserialization, its value is null.
Also Learn Important Topics of Java
- What are the operators in Java Programming?
- What are Data Types in Java?
- What are the Variables in Java?
- Learn Java syntax.
- What is Java if else statements?
- What is method overloading in Java?
- What are the Classes and Objects in Java?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.