
Java Class Attributes in Java
Class Attributes in Java
In Java, class attributes (also known as fields, variables, or members) are variables that are associated with a class. These variables store data or state that is shared across all instances of the class, or they can be specific to each object depending on how they are defined.
Class attributes can be of two types:
Instance Variables (Non-static attributes)
Static Variables (Class attributes)
1. Instance Variables (Non-static attributes)
Instance variables are declared inside a class but outside of any method, constructor, or block. Each instance of the class has its own copy of the instance variable, and the values of the instance variables may differ for each object.
Example:
public class Person { // Instance variables (attributes) String name; // Instance variable for storing name int age; // Instance variable for storing age // Constructor to initialize the instance variables public Person(String name, int age) { this.name = name; this.age = age; } // Method to display the person's details public void displayDetails() { System.out.println("Name: " + name); System.out.println("Age: " + age); } public static void main(String[] args) { // Creating objects (instances) of the Person class Person person1 = new Person("Alice", 25); Person person2 = new Person("Bob", 30); // Displaying details of each person person1.displayDetails(); person2.displayDetails(); }}
Output:
Name: AliceAge: 25Name: BobAge: 30
In the above example, the name
and age
attributes are instance variables. Each Person
object can have its own name
and age
.
2. Static Variables (Class Attributes)
Static variables are declared with the static
keyword. They are shared among all instances of the class, meaning every object of that class accesses the same variable. Static variables are typically used to store class-level data or constants.
Example:
public class Counter { // Static variable (class attribute) static int count = 0; // Shared across all instances // Constructor public Counter() { count++; // Increment the static count for every new object created } // Method to display the count public void displayCount() { System.out.println("Count: " + count); } public static void main(String[] args) { Counter counter1 = new Counter(); Counter counter2 = new Counter(); Counter counter3 = new Counter(); // Displaying the count for each object counter1.displayCount(); // Output: Count: 3 counter2.displayCount(); // Output: Count: 3 counter3.displayCount(); // Output: Count: 3 }}
Output:
Count: 3Count: 3Count: 3
In this example, the count
variable is a static variable. All three Counter
objects share the same count
variable, which gets incremented every time a new Counter
object is created.
Access Modifiers for Class Attributes
In Java, class attributes can have different access levels, controlled by access modifiers:
private
: The variable is accessible only within the same class.default
(no modifier): The variable is accessible within the same package.protected
: The variable is accessible within the same package and by subclasses (even in other packages).public
: The variable is accessible from any other class.
Example with Access Modifiers:
public class Car { // Private instance variable, accessible only within the Car class private String model; // Public static variable, accessible globally public static int numberOfCars; // Constructor to initialize instance variable public Car(String model) { this.model = model; numberOfCars++; // Increment the static variable every time a new Car object is created } // Getter method to access private variable public String getModel() { return model; } public static void main(String[] args) { Car car1 = new Car("Toyota"); Car car2 = new Car("Honda"); System.out.println("Model of car1: " + car1.getModel()); // Output: Toyota System.out.println("Model of car2: " + car2.getModel()); // Output: Honda // Accessing the static variable System.out.println("Number of cars: " + Car.numberOfCars); // Output: 2 }}
Output:
Model of car1: ToyotaModel of car2: HondaNumber of cars: 2
In this example:
The
model
variable isprivate
, so it can only be accessed through thegetModel()
method.The
numberOfCars
variable ispublic static
, so it can be accessed and modified directly usingCar.numberOfCars
.
Default Values of Class Attributes
When class attributes (instance or static) are declared but not initialized, Java assigns them default values:
Instance Variables: Default values are assigned based on the type.
int
->0
boolean
->false
Object
references ->null
Static Variables: Same as instance variables, static variables are initialized with the default value unless explicitly initialized.
Example:
public class DefaultValues { // Instance variables int age; // Default value is 0 boolean isActive; // Default value is false // Static variables static String name; // Default value is null public static void main(String[] args) { DefaultValues obj = new DefaultValues(); System.out.println("Instance variable age: " + obj.age); // Output: 0 System.out.println("Instance variable isActive: " + obj.isActive); // Output: false System.out.println("Static variable name: " + name); // Output: null }}
Output:
Instance variable age: 0Instance variable isActive: falseStatic variable name: null
Class Attributes and Methods
You can access instance and static attributes in methods:
Instance Methods: Can access both instance and static variables.
Static Methods: Can only access static variables directly. To access instance variables, you need to create an object.
Example:
public class BankAccount { // Instance variables private double balance; // Static variable private static double interestRate = 5.0; // Constructor public BankAccount(double balance) { this.balance = balance; } // Instance method accessing both instance and static variables public void displayAccountDetails() { System.out.println("Balance: " + balance); System.out.println("Interest Rate: " + interestRate); } // Static method accessing only static variable public static void changeInterestRate(double newRate) { interestRate = newRate; } public static void main(String[] args) { BankAccount account = new BankAccount(1000); account.displayAccountDetails(); // Display balance and interest rate BankAccount.changeInterestRate(6.0); // Change static interest rate account.displayAccountDetails(); // Display updated interest rate }}
Output:
Balance: 1000.0Interest Rate: 5.0Balance: 1000.0Interest Rate: 6.0
In this example:
The
displayAccountDetails()
method is an instance method and can access bothbalance
(instance variable) andinterestRate
(static variable).The
changeInterestRate()
method is static and can only accessinterestRate
directly.
Summary
Instance Variables: Specific to each object, different values for each instance.
Static Variables: Shared across all instances of the class, only one copy exists.
Access Modifiers: Control visibility of class attributes (e.g.,
private
,public
,protected
).Default Values: Instance and static variables are initialized to default values if not explicitly initialized.
Accessing in Methods: Instance methods can access both instance and static variables, while static methods can only access static variables.
Let me know if you'd like more details or have other questions! ?