Java - Class Attributes
Java - Class Attributes
A class attribute defines the state of the class during program execution. A class attribute is
accessible within class methods by default.
For example, there is a class "Student" with some data members (variables) like roll_no, age, and
name. These data members are considered class attributes.
Syntax
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
In above class, we've fields like breed, age, and color which are also known as class attributes.
Syntax
object_name.attribute_name;
class Dog {
// Declaring and initializing the attributes
String breed = "German Shepherd";
int age = 2;
String color = "Black";
}
Output
German Shepherd
2
Black
Syntax
object_name.attribute_name = new_value;
class Dog {
// Declaring and initializing the attributes
String breed = "German Shepherd";
int age = 2;
String color = "Black";
}
// Printing
System.out.println("\nAfter modifying:");
System.out.println(obj.breed);
System.out.println(obj.age);
System.out.println(obj.color);
}
}
Output
Before modifying:
German Shepherd
2
Black
After modifying:
Golden Retriever
3
Golden
Syntax
Use the below syntax to make class attribute read-only:
In the below example, the name attribute is set to read-only using the final keyword. Now this
attribute can not be modified and JVM will complain if we try to modify this attribute.
package com.tutorialspoint;
class Dog {
final String name = "Tommy";
}
Output
Compile and run Tester. This will produce the following result −
at com.tutorialspoint.Tester.main(Tester.java:10)