Java Intermediate

0% completed

Previous
Next
Using Member Variables

In Java, member variables (also known as fields) are variables declared within a class but outside any method, constructor, or block. These variables represent the properties or state of an object. By using member variables, you can store and manage data specific to each instance of a class.

1. Defining Member Variables

Member variables are declared inside a class and define the attributes or properties of that class. They can have different access modifiers (private, public, etc.) to control their visibility.

Syntax:

class ClassName { // AccessModifier dataType variableName; AccessModifier dataType variableName; }

Explanation:

  • AccessModifier: Controls who can see or use the variable.
  • dataType: The type of data the variable holds.
  • variableName: The name of the variable, typically in camelCase.

Note: We will learn more about access modifiers in the Encapsulation chapter.

Example:

Java
Java
. . . .

2. Updating Member Variables

Member variables can be updated by assigning new values to them using the object reference.

Syntax:

objectName.variableName = value;

Explanation:

  • objectName: The reference to the object whose member variable you want to update.
  • variableName: The name of the member variable you want to update.
  • value: The new value you want to assign to the member variable. The value must be compatible with the variable's data type.

Example:

Java
Java

. . . .

Explanation:

  • We create a Car object.
  • We update its brand, color, and year member variables.
  • Finally, we print them to confirm the updates.

3. Accessing Member Variables

After assigning values to member variables, we can retrieve them via the object reference.

Syntax:

dataType value = objectName.variableName;

Explanation:

  • dataType: The type of data the variable holds.
  • value: A new variable that will store the accessed value.
  • objectName.variableName: Accesses the member variable variableName from the object objectName.

Example:

Java
Java

. . . .

Explanation:

  • We create an Animal object.
  • We assign values to species and age.
  • We retrieve those values into local variables.
  • We print them directly, and also call a method that uses the member variables.

Member variables are crucial for storing an object’s state. In this lesson, we learned how to define, update, and access these variables in Java. Through examples using Car and Animal classes, you can now handle member variables to manage object properties in your programs.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next