Java
Java Classess
Java Class Attributes

Java Class Attributes

In the previous chapter, we used the term "variable" for x in the example. It is actually an attribute of the class. Class attributes are variables within a class:

Example: Define Class Attributes

public class Main {
  int x = 5;
  int y = 3;
}

Another term for class attributes is fields.

Accessing Attributes

You can access attributes by creating an object of the class and using the dot syntax (.):

public class Main {
  int x = 5;
 
  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}

Modify Attributes

You can modify attribute values:

public class Main {
  int x;
 
  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.x = 40;
    System.out.println(myObj.x);
  }
}

Or override existing values:

public class Main {
  int x = 10;
 
  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.x = 25;
    System.out.println(myObj.x);
  }
}

If you don’t want to allow modification, declare the attribute as final:

public class Main {
  final int x = 10;
 
  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.x = 25; // Error: cannot re-assign a value to a final variable
  }
}

The final keyword ensures that a variable always stores the same value, like PI (3.14159...).

Multiple Objects with Different Attribute Values

You can change attribute values in one object without affecting others:

public class Main {
  int x = 5;
 
  public static void main(String[] args) {
    Main myObj1 = new Main();
    Main myObj2 = new Main();
    myObj2.x = 25;
    System.out.println(myObj1.x);
    System.out.println(myObj2.x);
  }
}

Multiple Attributes

A class can have multiple attributes:

public class Main {
  String fname = "John";
  String lname = "Doe";
  int age = 24;
 
  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);
    System.out.println("Age: " + myObj.age);
  }
}

The next chapter will teach you how to create class methods and access them with objects.