Java Class Attributes

Variables that store data in classes

📊 What are Class Attributes?

Class attributes are variables declared inside a class that store data for objects. Each object has its own copy of these attributes with different values, defining the object's state and characteristics.


class Phone {
    String brand;     // Attribute
    String model;     // Attribute
    int storage;      // Attribute
    boolean isOn;     // Attribute
}
                                    

Types of Attributes

🔤

String

Text data

String name = "John";
🔢

int

Whole numbers

int age = 25;
💰

double

Decimal numbers

double price = 99.99;
✅

boolean

True or false values

boolean isActive = true;

🔹 Declaring Attributes

Attributes are declared inside the class but outside any methods:

// Student.java
public class Student {
    // Class attributes (instance variables)
    String firstName;
    String lastName;
    int studentId;
    double gpa;
    boolean isEnrolled;
    char grade;
    
    // Methods will go here...
    void displayInfo() {
        System.out.println("Student: " + firstName + " " + lastName);
        System.out.println("ID: " + studentId);
        System.out.println("GPA: " + gpa);
        System.out.println("Enrolled: " + isEnrolled);
        System.out.println("Grade: " + grade);
    }
}

Key Points:

  • Attributes are declared at the class level
  • Each object gets its own copy of attributes
  • Attributes can be different data types
  • Default values are assigned if not initialized

🔹 Accessing and Modifying Attributes

You can access and modify attributes using the dot (.) operator:

// StudentExample.java
public class StudentExample {
    public static void main(String[] args) {
        // Create a student object
        Student student1 = new Student();
        
        // Set attribute values
        student1.firstName = "Emma";
        student1.lastName = "Johnson";
        student1.studentId = 12345;
        student1.gpa = 3.8;
        student1.isEnrolled = true;
        student1.grade = 'A';
        
        // Display student info
        student1.displayInfo();
        
        System.out.println("---");
        
        // Modify attributes
        student1.gpa = 3.9;
        student1.grade = 'A';
        
        System.out.println("After grade update:");
        student1.displayInfo();
    }
}

Output:

Student: Emma Johnson
ID: 12345
GPA: 3.8
Enrolled: true
Grade: A
---
After grade update:
Student: Emma Johnson
ID: 12345
GPA: 3.9
Enrolled: true
Grade: A

🔹 Default Values

If you don't initialize attributes, Java assigns default values:

// DefaultValues.java
class DefaultExample {
    String text;        // Default: null
    int number;         // Default: 0
    double decimal;     // Default: 0.0
    boolean flag;       // Default: false
    char character;     // Default: '\u0000' (null character)
    
    void showDefaults() {
        System.out.println("String: " + text);
        System.out.println("int: " + number);
        System.out.println("double: " + decimal);
        System.out.println("boolean: " + flag);
        System.out.println("char: '" + character + "'");
    }
}

public class DefaultValues {
    public static void main(String[] args) {
        DefaultExample obj = new DefaultExample();
        obj.showDefaults();
    }
}

Output:

String: null
int: 0
double: 0.0
boolean: false
char: ''

🔹 Initializing Attributes

You can initialize attributes when declaring them:

// Car.java
class Car {
    // Initialized attributes
    String brand = "Unknown";
    String color = "White";
    int year = 2023;
    double price = 0.0;
    boolean isElectric = false;
    int mileage = 0;
    
    void displayCar() {
        System.out.println("=== Car Details ===");
        System.out.println("Brand: " + brand);
        System.out.println("Color: " + color);
        System.out.println("Year: " + year);
        System.out.println("Price: $" + price);
        System.out.println("Electric: " + isElectric);
        System.out.println("Mileage: " + mileage + " miles");
    }
}

// CarExample.java
public class CarExample {
    public static void main(String[] args) {
        // Create car with default values
        Car car1 = new Car();
        System.out.println("Car 1 (default values):");
        car1.displayCar();
        
        // Create another car and customize
        Car car2 = new Car();
        car2.brand = "Tesla";
        car2.color = "Red";
        car2.year = 2024;
        car2.price = 45000.0;
        car2.isElectric = true;
        car2.mileage = 1500;
        
        System.out.println("\nCar 2 (customized):");
        car2.displayCar();
    }
}

Output:

Car 1 (default values):
=== Car Details ===
Brand: Unknown
Color: White
Year: 2023
Price: $0.0
Electric: false
Mileage: 0 miles

Car 2 (customized):
=== Car Details ===
Brand: Tesla
Color: Red
Year: 2024
Price: $45000.0
Electric: true
Mileage: 1500 miles

🔹 Best Practices

Naming Conventions:

  • camelCase: firstName, lastName, studentId
  • Descriptive: Use meaningful names
  • No spaces: Use camelCase instead

Good Practices:

  • Initialize attributes with sensible default values
  • Use appropriate data types
  • Group related attributes together
  • Consider using private attributes with getter/setter methods

🧠 Test Your Knowledge

What is the default value of a boolean attribute in Java?