Java Class Attributes
The variables declared inside a class are called attributes or, more commonly in Java, fields. They hold the state of each object. In this chapter you'll see how to give fields initial values, how to protect them with final, and the difference between per-object fields and static fields shared by the whole class.
Declaring and accessing fields
class Product {
String name;
double price;
int stock = 0; // a field can have an initial value
}
class Main {
public static void main(String[] args) {
Product p = new Product();
p.name = "Headphones";
p.price = 59.90;
p.stock = 12;
System.out.println(p.name + " costs " + p.price + ", in stock: " + p.stock);
p.stock -= 3; // modify like any variable
System.out.println("After sale: " + p.stock);
}
}Headphones costs 59.9, in stock: 12
After sale: 9
You read and write fields with object.fieldName. Every new Product starts with stock = 0 because of the initializer.
Each object has its own copy
class Player {
String name;
int score = 100;
}
class Main {
public static void main(String[] args) {
Player p1 = new Player();
Player p2 = new Player();
p1.name = "Kim";
p2.name = "Sam";
p1.score += 50;
p2.score -= 20;
System.out.println(p1.name + ": " + p1.score);
System.out.println(p2.name + ": " + p2.score);
}
}Kim: 150
Sam: 80
final fields
A final field must be assigned exactly once — either where it's declared or in a constructor — and can never change afterwards. Use it for values that define an object's identity:
class Order {
final int id = 1001;
String status = "new";
}
class Main {
public static void main(String[] args) {
Order o = new Order();
o.status = "shipped"; // fine
// o.id = 2002; // error: cannot assign a value to final variable id
System.out.println("Order " + o.id + " is " + o.status);
}
}Order 1001 is shipped
static fields
A field marked static belongs to the class, not to any single object. There is exactly one copy, shared by all instances. It's accessed through the class name:
class Ticket {
static int issued = 0; // shared by all tickets
int number; // one per ticket
Ticket() {
issued++;
number = issued;
}
}
class Main {
public static void main(String[] args) {
Ticket a = new Ticket();
Ticket b = new Ticket();
Ticket c = new Ticket();
System.out.println("a=" + a.number + " b=" + b.number + " c=" + c.number);
System.out.println("Total issued: " + Ticket.issued);
}
}a=1 b=2 c=3
Total issued: 3
Ticket() is a constructor — code that runs whenever a new object is created. Constructors get their own chapter soon.
Constants
Combining static and final creates a class-level constant. By convention constants are named in UPPER_SNAKE_CASE. The JDK is full of them, like Math.PI and Integer.MAX_VALUE:
class Shipping {
static final double FREE_SHIPPING_FROM = 50.0;
static final double FLAT_RATE = 4.95;
static double cost(double orderTotal) {
return orderTotal >= FREE_SHIPPING_FROM ? 0 : FLAT_RATE;
}
}
class Main {
public static void main(String[] args) {
System.out.println(Shipping.cost(30));
System.out.println(Shipping.cost(75));
System.out.println("Free from " + Shipping.FREE_SHIPPING_FROM);
}
}4.95
0.0
Free from 50.0
Summary
| Kind of field | Copies | Access | Typical use |
|---|---|---|---|
| instance field | one per object | obj.field |
an object's state |
final instance field |
one per object, fixed | obj.field |
IDs, immutable values |
static field |
one per class | ClassName.field |
counters, shared settings |
static final field |
one per class, fixed | ClassName.FIELD |
constants |
Tip: Accessing fields directly from outside the class (as in these examples) is convenient for learning, but real code usually makes fields
privateand offers methods instead. That's the topic of the Encapsulation chapter.
Test yourself
How many copies of a static field exist when you create 10 objects?
- 0
- 1
- 10
- 11
What is the naming convention for static final constants?
- camelCase
- PascalCase
- UPPER_SNAKE_CASE
- kebab-case
What happens if you assign to a final field a second time?
- The old value is kept
- A runtime exception
- A compile error
- The field becomes non-final