In this section, we will learn what the class fields are and how to use them in Java.
What Is Java Field?
Objects have attributes.
Take a car, for example:
A car has attributes, for example its color, weight, speed, horse-power, model, and brand etc.
A Computer is another example of an object with attributes:
Its monitor size, the number of CPU core, the amount of RAM, the size of its hard-disk etc.
All the information that we can get from an object are basically the attributes of that object.
In the world of Java, we can set attributes for objects we create in a program.
Notes: attributes are also called `fields` of a class and so we might use them interchangeably.
We set attributes inside a class (out of any method of that class) and any object that is created from that class will get a copy of those attributes.
Field Declaration Syntax
To declare a field, we follow the same syntax that is used to create a variable. This is because, at its core, a field is nothing but a variable.
[access-modifier] [data-type] [attribute-name];
Example: creating fields in a Java Class
Note: if you want to store this class and use it in your IDE, make sure the name of the file is the same as the name of the class, which is Human.
public class Human { public String name; public String lastName; public int height; public int weight; public String colorEyes; }
How Does Fields Work in Java Class?
In this example, we could add as many attributes as we could find for a human, but for the sake of simplicity, we decided to go with just a few of them for now.
A human has hundreds, if not thousands of attributes. But we don’t need to include all the attributes we could find for a human in the program. Basically, we need to think about why we need an object in a program and what attributes of that object is useful in the program.
For example, if we don’t need the number of teeth of a human in a program, then why should we have an attribute about this in a class of type `Human`?
So before writing a class, think about those attributes you might need and then design the class.
As mentioned before, the attributes of a class are declared outside of any method and usually right after the opening brace `{` of the class. But of course, this is optional and we can declare the attributes anywhere in that class as long as it’s not inside a block of code.
Attributes in a class are basically just variables, but because they are declared in the class and not inside a method of that class, we call them attributes.
Note: variables that are in the methods of a class are called local variables.
Java Initial Field Value
We can initialize a field right where it’s being declared. For this to happen, we use the assignment operator and the value on the right side of the operator to be assigned.
Example: initializing fields in Java Class
public class Human { public String name = "John"; public String lastName = "Doe"; public int height = 200; public int weight = 95; public String colorEyes = "Blue"; }
Java Field access modifiers
The access specifier of an attribute can be either `private`, `public` or `protected`.
If we don’t declare the accessibility of a variable, by default it will be accessible within the package that the class is defined. This means if we create an object in the same package that the class is defined in, that object has the access to these attributes. But if we create an object from such a class but in a separate package, that object cannot access the attributes that didn’t explicitly declare their access specifiers as `public`.
Usually it’s a good practice to declare the attributes of a class as private and limit the access to those attributes via methods of that class. This is because an attribute that is declared as `public` or default can be accessed directly from objects outside of the class and we can’t control the range of values that would be set to the attributes. So someone might un-intentionally or intentionally change the value of the attribute in a way that we don’t want (More on this in methods section).
For now, let’s create an object from the `Human` class that we’ve just created at the beginning of this section and see how we can access and change the attributes of such an object:
Example: Java Field Access Modifiers
public class Simple { public static void main(String[] args) { Human john = new Human(); john.eyesColor = "Blue"; john.height = 180; john.weight = 75; john.name = "John"; john.lastName = "Doe"; System.out.println("Name: "+john.name); System.out.println("Last Name: "+john.lastName); System.out.println("Eyes Color: "+ john.eyesColor); System.out.println("Weight: "+john.weight); System.out.println("Height: "+john.height); } }
Output:
Name: John Last Name: Doe Eyes Color: Blue Weight: 75 Height: 180
Note: The file that the `Human` class is declared in, should be in the same directory that the `Simple` class is in as well. Or if you’re using an IDE, make sure both classes are in the same package.
Java Accessing Fields in Objects
When we create an object from a class, the attributes of that object are still variables and, just like the way we use variables as LValues and RValues, we can use these attributes the same way.
The important note here is how we access the attributes of an object:
Java Accessing Object Fields Syntax:
We use the dot `.` operator between the name of the target object and its public attribute:
objectName.atributeName;
Example: accessing object fields in Java
jack.name; jack.lastName;
Notes:
- The use of dot `.` operator is not limited to just the attributes of an object, but to any member of that object (including methods).
- Also, these members (attributes or methods) should not be declared as `private` otherwise we can’t access those members.
In this example, as you can see, because the attributes are public, we could access them, set and get their values.
But if those attributes were `private` any attempt to access those values would return compile time error.
Note: also if those attributes were `protected` only objects that were created in the same package could access those attributes. If the objects of type of a class were in different package than the one that the class itself was, we could not access protected members (attributes as well as methods).
Example: accessing private fields of a Java object
Now change the access specifier of the attributes in the `Human` class to `private` like this:
public class Human { private String name; private String lastName; private int height; private int weight; private String eyesColor; }
Then go to the `Simple` class and run the program:
public class Simple { public static void main(String[] args) { Human john = new Human(); john.eyesColor = "Blue"; john.height = 180; } }
Output:
Error:(7, 13) java: height has private access in tuto.Human Error:(6, 13) java: eyesColor has private access in tuto.Human
As you can see, the moment we compile the program, we get these two errors which are saying the two attributes named `height` and `eyesColor` are basically `private` members and we’re trying to access them from an object!
Even though a private attribute is no-longer accessible from an object, this is a good practice and it allows us to develop public methods for that class and limit the access only via those methods.
In method section we will explain in depth, but for now, remember that a method of a class has the access to the private members of that class.
Java Final Fields
If we want to initialize a field once and never change its value, we can use the `final` keyword.
To declare a field as final, we add the keyword `final` to the declaration of the target field.
Note: If you’re not familiar with the `final` keyword, please refer to the mentioned section.
Example: final fields in Java
public class Human { public final String name = "John"; public final String lastName = "Doe"; public final int height = 200; public final int weight = 95; public final String colorEyes = "Blue"; }
So here the `name`, `lastName`, `height`, `weight`, and `colorEyes` fields are final and we can’t change their value anymore.