๐ŸŽ“ A1Learner
๐Ÿ”

Java Class Attributes

Class attributes are the fields declared inside a class. Each object stores its own copy of every field.

Fields of several types

The Person class declares a String field, an int field, and a double field. Each print line reads one field through the object.

class Person {
  String name = "Ada";
  int age = 36;
  double height = 1.68;
}

public class Main {
  public static void main(String[] args) {
    Person person = new Person();
    System.out.println(person.name);
    System.out.println(person.age);
    System.out.println(person.height);
  }
}

A change touches one object only

The first object takes a new name. The second object keeps the name from the class, and both prints prove the split.

class Person {
  String name = "Ada";
  int age = 36;
  double height = 1.68;
}

public class Main {
  public static void main(String[] args) {
    Person first = new Person();
    Person second = new Person();
    first.name = "Mia";
    System.out.println(first.name);
    System.out.println(second.name);
  }
}

A field takes a new value

The first print shows the starting age. The assignment stores 37, and the second print shows the new value.

class Person {
  String name = "Ada";
  int age = 36;
  double height = 1.68;
}

public class Main {
  public static void main(String[] args) {
    Person person = new Person();
    System.out.println(person.age);
    person.age = 37;
    System.out.println(person.age);
  }
}

Example

class Person {
  String name = "Ada";
  int age = 36;
  double height = 1.68;
}

public class Main {
  public static void main(String[] args) {
    Person first = new Person();
    Person second = new Person();
    second.name = "Ben";
    second.age = 24;
    System.out.println(first.name + ", " + first.age);
    System.out.println(second.name + ", " + second.age);
  }
}

Key points

  • A field holds one value for its object.
  • A class can declare fields of different types.
  • A dot writes a new value into a field of one object.
  • A change to one object leaves other objects unchanged.
  • A field keeps the value written in the class until code changes it.

In this example, two Person objects start with the same field values. The code changes the name and age of the second object only. The prints show Ada with 36 and Ben with 24, so each object kept its own copy of the fields.

Note

A field is also called a class attribute.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

What happens to a second object when a field of the first object changes?