Class Attributes in Java
Class attributes in Java are variables that belong to a class and represent the properties or characteristics of objects created from that class.
In Java, class attributes are also known as fields or member variables. They store the data of an object and define its state.
For example, a Student class can have attributes like name, age, and rollNumber that describe the properties of a student object.
What are Class Attributes in Java?
A class attribute is a variable declared inside a class but outside any method, constructor, or block.
Each object created from a class can have its own values for these attributes. These attributes define what information an object stores.
Syntax of Class Attributes in Java
class ClassName {
dataType attributeName;
}
Example of Class Attributes in Java
class Student {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "John";
s1.age = 20;
System.out.println(s1.name);
System.out.println(s1.age);
}
}
20
Types of Class Attributes in Java
Java class attributes are mainly divided into different types based on their behavior and declaration.
Instance Attributes
Variables that belong to individual objects. Every object has its own copy of instance attributes.
Static Attributes
Variables declared with the static keyword. They are shared among all objects of a class.
Final Attributes
Variables declared with final keyword whose values cannot be changed.
Instance Attributes in Java
Instance attributes are non-static variables that belong to an object. Every object gets a separate copy of these attributes.
class Car {
String color;
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car();
car1.color = "Red";
car2.color = "Black";
System.out.println(car1.color);
System.out.println(car2.color);
}
}
Black
Static Attributes in Java
A static attribute belongs to the class instead of individual objects. Only one copy of a static attribute is created and shared by all objects.
class Student {
static String school = "ABC School";
}
public class Main {
public static void main(String[] args) {
System.out.println(Student.school);
}
}
Accessing Class Attributes in Java
Class attributes can be accessed using the object name or class name depending on whether they are instance or static attributes.
- Instance attributes are accessed using object references.
- Static attributes are accessed using the class name.
- Access modifiers control the visibility of attributes.
Access Modifiers for Class Attributes
public
Accessible from anywhere in the program.
private
Accessible only inside the same class.
protected
Accessible within the same package and subclasses.
Advantages of Class Attributes in Java
Store Data
Used to store object information and properties.
Code Organization
Helps organize related data inside classes.
Object Modeling
Helps represent real-world entities in programs.