Java Class Attributes
Class attributes in Java are variables declared within a class but outside any method. They represent the properties or data that objects of the class can have.
1. Types of Attributes
2. Instance Variables
Instance variables are unique to each instance (object) of the class. They are declared without the static
keyword.
public class Person {
String name; // Instance variable
int age; // Instance variable
}
3. Class Variables (Static Variables)
Class variables are shared among all instances of the class. They are declared with the static
keyword.
public class Person {
static String species = "Homo sapiens"; // Class variable
}
4. Access Modifiers
Access modifiers determine the visibility of class attributes:
public
: Accessible from any other class.private
: Accessible only within the declared class.protected
: Accessible within the same package or subclasses.default
(no modifier): Accessible within the same package.
5. Example
public class BankAccount {
private double balance; // Private instance variable
public String accountNumber; // Public instance variable
public static double interestRate = 0.05; // Public class variable
}
Key Takeaways
- Class attributes store the state of objects.
- Instance variables are unique to each object, while class variables are shared.
- Use access modifiers to control the visibility and encapsulation of attributes.
- Proper attribute management is crucial for object-oriented design.